Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql last month date statement

Tags:

date

php

mysql

I have a DATE, how do I write a where that checks for last month until now (either the first of or just today's day -1 month)?

like image 967
An employee Avatar asked Sep 25 '09 21:09

An employee


2 Answers

Actually, last month until now would be:

From the beginning of the month:

SELECT * FROM table
WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-01')
AND date <= NOW()

Since a month ago: (hopefully you have no future dates on the table)

SELECT * FROM table
WHERE date >= (CURRENT_DATE - INTERVAL 1 MONTH)

Alternatively, you might want only the last month... Say today is September and you want all August, not including any of September... That is what I understand as 'last month'.

SELECT * FROM table
WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01')
AND date < DATE_FORMAT(CURRENT_DATE, '%Y/%m/01')

You could also do for the same result:

SELECT * FROM table
WHERE YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
like image 90
mimoralea Avatar answered Nov 15 '22 16:11

mimoralea


SELECT * FROM table WHERE dateField > DATE_SUB(NOW(), INTERVAL 1 MONTH)

This selects all rows that have a dateField more recent than current timestamp minus one month (so, for example, given today is 26 Sep 2009 00:56 it would give rows that are more recent than 26 Aug 2009 00:56)

like image 26
andri Avatar answered Nov 15 '22 16:11

andri