Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Where date is greater than one month?

Tags:

mysql

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

like image 321
JasonS Avatar asked Nov 21 '10 11:11

JasonS


People also ask

Where date is greater than current date in SQL?

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.

Which date is greater in MySQL?

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.

How do I get last 3 months data in SQL?

In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.


2 Answers

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)

like image 108
Matt Healy Avatar answered Oct 19 '22 05:10

Matt Healy


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.

like image 39
T.J. Crowder Avatar answered Oct 19 '22 06:10

T.J. Crowder