Table:
Id Date
1 01-10-15
2 01-01-16
3 01-03-16
4 01-06-16
5 01-08-16
鉴于两个日期 startdate 01-02-16和 enddate 01-05-16。我需要从表中获取数据,以便返回 startdate 中最接近的过去日期与 enddate 最近的日期之间的所有数据,包括两个日期。所以结果会是这样的。
Result:
Id Date
2 01-01-16
3 01-03-16
4 01-06-16
我在做什么
我现在正在做的是获取整个数据并从数组中删除少于最接近的 fromdate 并且大于最接近的 enddate
我想要什么
我想要的是在查询中执行此操作,这样我就不必每次都从表中获取整个数据。
答案 0 :(得分:2)
如果您的列类型为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')
答案 1 :(得分:2)
您的日期成像时间为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
答案 2 :(得分:1)
试试这个
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)
答案 3 :(得分:0)
如果Date是String,则可以在此处使用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)