MySQL Select last month data by current_timestamp

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

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) ?

回答1:

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.



回答2:

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()) 


回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!