Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select last month data by current_timestamp

till today when i was working with MySQL and needed to perform actions with date/time i was using int column with unix timestamp and there was no problems, but today after reading some guides i decided to test timestamp column with "current_timestamp" by default.

So i am interested how to select last month data by column where info is in "2012-09-07 00:23:30" format? And maybe there some tricky queries what will give me data from the start of this month (not last 30 days, but from 09-01 00:00:00 till today) ?

like image 735
MyMomSaysIamSpecial Avatar asked Sep 06 '12 22:09

MyMomSaysIamSpecial


1 Answers

This will give you the last month:

WHERE dateColumn BETWEEN SUBDATE(CURDATE(), INTERVAL 1 MONTH) AND NOW();

This from the start of the month:

WHERE dateColumn BETWEEN STR_TO_DATE('2012-09-01', '%Y-%m-%d') AND NOW();

The BETWEEN is nothing special, it's just a shortcut for

dateColumn <= ... AND dateColumn >= ....

Hmm, I guess the NOW() comparison is not actually needed, since all the records will be before now.

So just do:

WHERE dateColumn >= STR_TO_DATE('2012-09-01', '%Y-%m-%d')

Dynamic start of current month:

WHERE dateColumn >= CURDATE() - INTERVAL DAY(CURDATE())-1 DAY

All this does is extract the day of the month from the current date, then subtract that many days less one from it.

like image 118
Ariel Avatar answered Sep 28 '22 02:09

Ariel