MySQL 查找过去 24 小时内带有日期字段的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8079671/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:38:14  来源:igfitidea点击:

Find records with a date field in the last 24 hours

mysqlsqldate

提问by user1022585

In my SQL query how do i make it find the records in the last 24 hours? Eg

在我的 SQL 查询中,我如何让它找到过去 24 小时内的记录?例如

   SELECT * FROM news WHERE date < 24 hours

I usually do it by setting a variable to date() - 1 day and comparing it to that but I wondered whether the sql query way was faster?

我通常通过将变量设置为 date() - 1 天并将其与该变量进行比较来实现,但我想知道 sql 查询方式是否更快?

回答by a'r

You simply select dates that are higher than the current time minus 1 day.

您只需选择比当前时间减去 1 天的日期。

SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;

回答by Andrew

SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

回答by giuseppe

SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);

回答by NarayanaReddy

To get records from the last 24 hours:

要获取过去 24 小时的记录:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

回答by Craig Labenz

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

有很多方法可以做到这一点。列出的那些工作得很好,但如果你有一个日期时间字段,这是另一种方式:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff()returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

timediff()返回一个时间对象,所以不要错误地将它与 86400(一天中的秒数)进行比较,否则你的输出将是各种各样的错误。

回答by Simon

SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())

回答by Lasse Edsvik

SELECT * FROM news WHERE date < DATEADD(Day, -1, date)