I have a datetime column called 'last_login'.
I want to query my database to select all records that haven't logged in within the last month. How do I do this?
This is what I have currently:
$query = $this->query("SELECT u.id, u.name, u.email, u.registered, g.name as group_name FROM `:@users` AS u LEFT JOIN `:@groups` AS g on u.group_id = g.id WHERE u.last_login = ...... LIMIT {$limit_start}, {$limit_end}");
:@ = database prefix
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a 'YYYY-MM-DD hh:mm: ss. mmm' pattern.
MySQL where date greater than 30 days agoDATE(expression): Will get the date value from the DATE or DATETIME expression passed in as a parameter. CURDATE(): Will return current date either in 'YYYY-MM-DD' or 'YYYYMMDD' format depending on if the curdate() function is used in a string or numeric context.
In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.
Try using date_sub
where u.last_login < date_sub(now(), interval 1 month)
(Similar to the first answer but in my mind it is more "natural" to use positive integers)
You can use date_add
combined with now
:
...where u.last_login < date_add(now(), interval -1 month)
Naturally, as both are MySQL-specific this limits you to MySQL backends. Alternately, you can figure out what the date was a month ago with PHP (I'm not a PHP person, but I'm guessing DateTime::sub
would help with that) and then include that date in your query in the normal way you would any other date/time field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With