简体   繁体   English

MySQL选择哪里列大于或等于给定日期的最近过去日期

[英]MySQL Select where column greater than or equal to closest past date from given date

TABLE

Table:

Id             Date
1            01-10-15
2            01-01-16
3            01-03-16
4            01-06-16
5            01-08-16

Given two dates startdate 01-02-16 and enddate 01-05-16. 给定两个日期起始日期 16年1月2日日期结束日期 16年1月5日。 I need to get the data from the table such that it returns all data between the closest past date from startdate and closest future date from enddate including the two dates. 我需要从表中,使得它返回从开始日期最接近过去的日期和结束日期 ,包括两个日期最近的未来日期之间的所有数据获得的数据。 So the result will look like this. 因此结果将如下所示。

Result:

Id             Date
2            01-01-16
3            01-03-16
4            01-06-16

What I am doing 我在做什么

What I am doing now is fetching the whole data and removing from the array results less than closest fromdate and greater than closest enddate 我现在正在做的是获取整个数据并从数组中删除结果,其结果小于最接近的起始日期,而大于最接近的终止日期

What I want 我想要的是

What I want is to do this in query itself so that I don't have to fetch the whole data from table each time. 我想要在查询本身中执行此操作,这样就不必每次都从表中获取整个数据。

If you column's type is date , use union can do it: 如果列的类型为date ,则使用union可以做到这一点:

(select * from yourtable where `date` <= '2016-01-02' order by `date` desc limit 1)
-- This query will get record which is closest past date from startdate
union
(select * from yourtable where `date` => '2016-01-05' order by `date` asc limit 1)
-- This query will get record which is closest future date from enddate
union
(select * from yourtable where `date` between '2016-01-02' and '2016-01-05')

Demo Here 在这里演示

Imaging your date is in YYYY-mm-dd 成像日期为YYYY-mm-dd

## get rows within the dates
SELECT * FROM tab WHERE ymd BETWEEN :start_date AND :end_date
## get one row closest to start date

UNION
SELECT * FROM tab WHERE ymd < :start_date ORDER BY ymd DESC LIMIT 1
## get one row closest to end date

UNION
SELECT * FROM tab WHERE ymd > :end_date   ORDER BY ymd      LIMIT 1

Try this 尝试这个

Select *
From 
    dTable 
Where 
     [Date] 
Between 
       (Select 
              Max(t1.Date) 
        From 
            dTable t1 
        Where 
             t1.date <startdate) And    
       (Select 
              Min(t2.Date) 
        From 
             dTable t2 
        Where 
             t2.date >enddate)

If Date is String, STR_TO_DATE and DATEDIFF can be used here. 如果日期为字符串,则可以在此处使用STR_TO_DATE和DATEDIFF。

SELECT  id,  Date
FROM tab
where
STR_TO_DATE(Date, '%d-%m-%y') BETWEEN('2016-02-01')AND('2016-05-01')
or 
id = (SELECT id FROM tab
where STR_TO_DATE(Date, '%d-%m-%y') > '2016-05-01'
ORDER BY DATEDIFF(STR_TO_DATE(Date, '%d-%m-%y'), '2016-05-01') Limit 1)
or 
id = (SELECT id FROM tab
where STR_TO_DATE(Date, '%d-%m-%y') < '2016-02-01'
ORDER BY DATEDIFF('2016-02-01', STR_TO_DATE(Date, '%d-%m-%y')) Limit 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM