SQL选择过去45天的所有数据

时间:2018-05-10 09:41:00

标签: mysql sql

我有"警告"带有日期字段的表 - targetDate。

我想选择过去45天的所有数据。

我尝试了下面的代码,但它没有返回任何结果...

SELECT userID, refID, `targetDate`
FROM alerts
WHERE type = 'travelSoon'
AND DATEDIFF( CURDATE( ) , targetDate ) > 45

 id     userID  type    refID   createDate  targetDate  lastSendDate    sent    valid
1   26  travelSoon  NO  2018-05-02 13:54:25 0000-00-00  2018-05-02 00:00:00 0   1
2   26  travelSoon  NO  2018-05-02 13:55:50 2018-06-01  0000-00-00 00:00:00 0   1
3   26  travelSoon  DK  2018-05-02 13:56:12 2018-12-01  0000-00-00 00:00:00 0   1
4   26  travelSoon      2018-05-02 13:59:50 0000-00-00  0000-00-00 00:00:00 0   1
5   26  travelSoon      2018-05-02 14:00:09 2018-08-01  0000-00-00 00:00:00 0   1
6   26  travelSoon  DK  2018-05-02 14:00:48 2018-08-01  0000-00-00 00:00:00 0   1
7   26  travelSoon      2018-05-02 16:45:18 2018-05-01  0000-00-00 00:00:00 0   1
8   26  travelSoon  RO  2018-05-02 16:45:45 2018-04-01  0000-00-00 00:00:00 0   1

3 个答案:

答案 0 :(得分:1)

使用DATEDIFF()是一个坏主意。它阻碍了使用索引的能力,并且有一种替代方案不会......

SELECT *
  FROM alerts
 WHERE type = 'travelSoon'

   AND targetDate >= DATEADD(DAY, -45, GETDATE())    -- SQL Server

   AND targetDate >= CURDATE() - INTERVAL 45 DAY     -- MySQL

http://www.sqlfiddle.com/#!9/4ecdc0/6

答案 1 :(得分:0)

在MSSQL DATEDIFF(interval, date1, date2)中返回date2 - date1的间隔。

应从此列表中选择间隔:

- year, yyyy, yy = Year
- quarter, qq, q = Quarter
- month, mm, m = month
- dayofyear = Day of the year
- day, dy, y = Day
- week, ww, wk = Week
- weekday, dw, w = Weekday
- hour, hh = hour
- minute, mi, n = Minute
- second, ss, s = Second
- millisecond, ms = Millisecond`

然后使用:

SELECT userID, refID, `targetDate`
FROM alerts
WHERE type = 'travelSoon'
AND DATEDIFF(day, targetDate, GETDATE() ) > 45

对于MySQL,您可以使用TIMESTAMPDIFF(unit,date1,date2)返回date1 - date2的间隔。

可以从unit

中选择

MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

SELECT userID, refID, `targetDate`
FROM alerts
WHERE type = 'travelSoon'
AND TIMESTAMPDIFF(DAY, CURDATE( ), targetDate) > 45

答案 2 :(得分:0)

试试这个......

SELECT userid, refid, `targetdate` 
FROM   alerts 
WHERE  type = 'travelSoon' 
       AND Datediff(Curdate(), targetDate) < 45 -- or <=45 
       AND Datediff(Curdate(), targetDate) > 0 

在线演示:http://www.sqlfiddle.com/#!9/4ecdc0/4/0

如果您只使用Datediff(Curdate(), targetDate) < 45条件,则可能会返回过去和将来的日期。请参考下表。

Today: May 10, 2018

+----+-------------+
| id | targetDate  |  DATEDIFF(CURDATE(), targetDate) 
+----+-------------+
|  2 | -- |                             -22 
|  3 | -- |                            -205 
|  5 | -- |                             -83 
|  6 | -- |                             -83 
|  7 | 2018-05-01  |                               9 
|  8 | 2018-04-01  |                              39 
+----+-------------+ 

为避免这种情况,您可以使用其他条件......

Datediff(Curdate(), targetDate) > 0