Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select records for the past 3 months

Tags:

mysql

what will be the smartest way to select all rows from MySQL table for the past 3 months if the table has the following columns:

| id (int) | year (int)| month (int) |

Considering that if the current month & year are for example 2.2016 I need to select all records for 11.2015 & 12.2015 & 1.2016

It is easy if the current month is greater than 3 because all months that I need to select are in the same year so I can subtract 3 from the current month and run simple query

SELECT * FROM mytabe where year=2016 and month >= xx
like image 694
metost Avatar asked Dec 06 '25 23:12

metost


1 Answers

Select * from mytable where STR_TO_DATE(concat(year,"-",month,"-01"),'%Y-%m-%d')>date_sub(curdate(),Interval 3 month) ;

The above query will get fetch year and month from date 3 months before today

like image 167
undefined_variable Avatar answered Dec 09 '25 13:12

undefined_variable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!