![](/img/trans.png)
[英]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.