简体   繁体   中英

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. 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:

(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

## 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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