2016-11-10 69 views
1

我想選擇當前月份和接下來的2個月份之間的所有記錄,但是我無法這樣做,因爲年份會從2016年到2017年。如何在接下來的3個月中選擇所有記錄,包括當前的新記錄時

例如。

我想所有的記錄,從2016年11月至2017年一月

當前查詢(如下所示)我已經一直很好,直到這個月,因爲2016年11月+ 2個月= 2017年一月

select * from dateTable 
where month(t2.`END_DATE`) between month(curdate()) and 
month(DATE_ADD(curdate(), INTERVAL 2 MONTH)) 
and year(t2.`END_DATE`) = year(curdate()); 

這將返回0行,因爲這不能處理有兩年了,2016和2017年

我怎麼會去這樣做呢?

回答

0

這應該是你所需要的,但也有可能是一些這樣做的方法

select * from dateTable 
where `END_DATE` BETWEEN DATE_FORMAT(NOW() ,'%Y-%m-01') 
        AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 2 MONTH)) 

此查詢的結果將證明產生

SELECT DATE_FORMAT(NOW() ,'%Y-%m-01') as from_date, 
     LAST_DAY(DATE_ADD(NOW(), INTERVAL 2 MONTH)) as to_date 
01日期

今天,這將產生

from_date to_date 
2016-11-01 2017-01-31 
+0

太感謝你了RiggsFolly,該訣竅! :d –

0

嘗試使用完整日期時間與DATE_ADDDATE_DIFF函數。

select * from dateTable where t2.`END_DATE` 
between DATEADD(month, 
     DATEDIFF(month, 0, getdate() -- get difference to first day 
     ), 0) 
and DATEADD(month, 2, -- add 3 months interval to get first day of third 
     DATEADD(month, 
      DATEDIFF(month, 0, getdate() -- get difference to first day 
     ), 0)) 

如果你不得不從上個月使用DATEADD再次刪除的第一天,除去1秒獲得23:59:59

相關問題