[英]Select record(s) from mysql table where date is greater than or equal to today
[英]MySQL Select where column greater than or equal to closest past date from given date
Table:
Id Date
1 01-10-15
2 01-01-16
3 01-03-16
4 01-06-16
5 01-08-16
给定两个日期起始日期 16年1月2日日期和结束日期 16年1月5日。 我需要从表中,使得它返回从开始日期最接近过去的日期和结束日期 ,包括两个日期最近的未来日期之间的所有数据获得的数据。 因此结果将如下所示。
Result:
Id Date
2 01-01-16
3 01-03-16
4 01-06-16
我在做什么
我现在正在做的是获取整个数据并从数组中删除结果,其结果小于最接近的起始日期,而大于最接近的终止日期
我想要的是
我想要在查询本身中执行此操作,这样就不必每次都从表中获取整个数据。
如果列的类型为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')
成像日期为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
尝试这个
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)
如果日期为字符串,则可以在此处使用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.