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

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

   SELECT * FROM news WHERE date < 24 hours

我通常将变量设置为 date ()-1 day,然后将其与之进行比较,但我想知道 sql 查询方式是否更快?

130344 次浏览
SELECT * FROM news WHERE date < DATEADD(Day, -1, date)
SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())
SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

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

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

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.

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);