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

2

20

I am trying to get the total amount of registered 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 want the user of today(=Tuesday).

Ormiston answered 26/3, 2013 at 9:37 Comment(1)
Please see this Post #590152Vargo
A
33

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() )
Anguilla answered 26/3, 2013 at 10:6 Comment(0)
T
9

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".

Thong answered 1/5, 2014 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.