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) ?
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.
You should take a look at common_schema, it's easy to install and has lots of great tools, including a function called start_of_month()
that is exactly what you are looking for:
select * from your_table where your_column >= common_schema.start_of_month(now())
If you have a mysql timestamp, something like 2013-09-29 22:27:10
you can do this
select * from table WHERE MONTH(FROM_UNIXTIME(UNIX_TIMESTAMP(time)))=9;
Convert to unix, then use the unix time functions to extract the month, in this case 9 for september.