MySQL 从 NOW() -1 天中选择记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8544438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select records from NOW() -1 Day
提问by user1092780
Is there a way in a MySQL statement to order records (through a date stamp) by >= NOW() -1 so all records from the day before today to the future are selected?
在 MySQL 语句中是否有一种方法可以通过 >= NOW() -1 对记录进行排序(通过日期戳),以便选择从今天前一天到未来的所有记录?
回答by Jon Skeet
Judging by the documentation for date/time functions, you should be able to do something like:
SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
回答by William Dan Terry
Be aware that the result may be slightly different than you expect.
请注意,结果可能与您预期的略有不同。
NOW()
returns a DATETIME
.
NOW()
返回一个DATETIME
.
And INTERVAL
works as named, e.g. INTERVAL 1 DAY = 24 hours
.
而INTERVAL
作品的命名,例如INTERVAL 1 DAY = 24 hours
。
So if your script is cron'd to run at 03:00
, it will miss the first three hours of records from the 'oldest' day
.
因此,如果您的脚本被 cron'd 运行于03:00
,它将错过first three hours of records from the 'oldest' day
.
To get the whole day use CURDATE() - INTERVAL 1 DAY
. This will get back to the beginning of the previous day regardless of when the script is run.
得到一整天的使用CURDATE() - INTERVAL 1 DAY
。无论脚本何时运行,这都会回到前一天的开始。
回答by dasblinkenlight
You're almost there: it's NOW() - INTERVAL 1 DAY
你快到了:它是 NOW() - INTERVAL 1 DAY
回答by Marco Miltenburg
Sure you can:
你当然可以:
SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)
回答by Andrew Atkinson
Didn't see any answers correctly using DATE_ADD
or DATE_SUB
:
使用DATE_ADD
or没有看到任何正确答案DATE_SUB
:
Subtract 1 day from NOW()
减去 1 天 NOW()
...WHERE DATE_FIELD >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Add 1 day from NOW()
添加 1 天从 NOW()
...WHERE DATE_FIELD >= DATE_ADD(NOW(), INTERVAL 1 DAY)
回答by Michael de Oz
when search field is timestamp and you want find records from 0 hours yesterday and 0 hour today use construction
当搜索字段是时间戳并且您想查找昨天 0 小时和今天 0 小时的记录时使用构造
MY_DATE_TIME_FIELD between makedate(year(now()), date_format(now(),'%j')-1) and makedate(year(now()), date_format(now(),'%j'))
instead
反而
now() - interval 1 day