yoko Posted April 28, 2008 Share Posted April 28, 2008 Hi I have a table with columns name, user, date, comment. How can i get the last month entries? I mean a code that always shows the last month entries. Can i do it without using PHP codes and only MySQL codes? Quote Link to comment Share on other sites More sharing options...
fenway Posted April 28, 2008 Share Posted April 28, 2008 Assuming your date column is a DATE type, you can use "yourDateColumn >= CURDATE() - INTERVAL 1 MONTH". Of course, that depends on your definiton of "last" and "month". Quote Link to comment Share on other sites More sharing options...
yoko Posted April 28, 2008 Author Share Posted April 28, 2008 Thanks for reply. Today is 2008/4/28. Last month would be from 2008/3/1 to 2008/4/1. So until we reach 2008/5/1, the last month will be still from 2008/3/1 to 2008/4/1. Thanks Quote Link to comment Share on other sites More sharing options...
fenway Posted April 28, 2008 Share Posted April 28, 2008 Well, then you'll have to do some fun date math / manipulation to get the first day... get the current year/month, go back one, add the date part ('01'), and then use INTERVAL and BETWEEN. Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted April 28, 2008 Share Posted April 28, 2008 I am guessing that the end dates shown in the example (the first day of the next month) are not inclusive? If so, the following should work (untested and is probably not the only or quickest way) - SELECT your_columns FROM your_table WHERE PERIOD_ADD(REPLACE(LEFT(CURDATE(),7),'-',''),-1) = REPLACE(LEFT(your_date_column,7),'-','') The period_add function takes care of year/month roll-over/roll-under. Quote Link to comment Share on other sites More sharing options...
fenway Posted April 28, 2008 Share Posted April 28, 2008 You need a range... an equality won't work..? Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted April 28, 2008 Share Posted April 28, 2008 It's comparing the yyyymm one period (month) before the current date with the yyyymm from the date in the table. No range is necessary. Quote Link to comment Share on other sites More sharing options...
fenway Posted April 28, 2008 Share Posted April 28, 2008 It's comparing the yyyymm one period (month) before the current date with the yyyymm from the date in the table. No range is necessary. Sorry, I glanced over the period function... interesting approach. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.