Mysql DATE_SUB(NOW(), INTERVAL 1 DAY) 24 hours or weekday?

╄→尐↘猪︶ㄣ 提交于 2019-11-27 13:49:06

问题


I am trying to get the totaal amount of registerd users per day. At the moment i am using this

$sql = "SELECT name, email FROM users WHERE DATE_SUB(NOW(), INTERVAL 1 DAY) < lastModified"

but i am not sure if this works per day or per 24 hours?

For example, a user who registered 22 hours ago shouldn't be returned i just like the user of today(=Tuesday)


回答1:


lastModified is, presumably, a datetime. To convert this into a date you can simply wrap it in DATE() i.e. DATE(lastModified). DATE() returns the date part of a datetime value which is effectively 00:00 on that day.

SELECT
    name,
    email
FROM users
WHERE DATE(lastModified) = DATE( DATE_SUB( NOW() , INTERVAL 1 DAY ) )

Using this to match a WHERE though would be inefficient as all rows would require DATE applied to them and so it would probably scan the whole table. It is more efficient to compare lastModified to the upper and lower bounds you are looking for, in this case >= 00:00 on SUBDATE(NOW(),INTERVAL 1 DAY) and < 00:00 on NOW()

Therefore you can use BETWEEN to make your select giving the following.

SELECT
    name,
    email
FROM users
WHERE lastModified 
    BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 1 DAY ) )
    AND DATE ( NOW() )



回答2:


I think you need

SELECT
    name,
    email
FROM users
WHERE DATE(lastModified) = DATE( NOW() )

This effectively "rounds to the date only" and will therefore only match records "since midnight".



来源:https://stackoverflow.com/questions/15633653/mysql-date-subnow-interval-1-day-24-hours-or-weekday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!