简体   繁体   中英

MySQL Query to get all rows for 2 months ago

I need to do a select where I can chose to see results for current month, previous month, 1 month ago, 2 months ago, 3 months ago.

I found this question: MySQL: Query to get all rows from previous month , but I'm stuck with a filter that will get me all the results for 2 months ago from first to last day of the month.

I tried with this but it doesn't work:

SELECT * FROM table
AND MONTH(date_created) = MONTH(1 MONTH - INTERVAL 2 MONTH);

Try this:

SELECT * FROM table
WHERE MONTH(date_created) = MONTH(NOW() - INTERVAL 2 MONTH)
    AND (
          YEAR(date_created) = YEAR(NOW()) 
        OR 
          YEAR(date_created) = YEAR(NOW() - INTERVAL 2 MONTH)
    );

Returning records CREATED PRIOR the last 2 months only in MySQL.

If you want all rows from 2 months ago, then use logic like this:

WHERE date_created >= DATE_SUB(DATE_SUB(CURDATE(), 1 - DAY(CURDATE())), INTERVAL 2 MONTH) AND
      date_created < DATE_SUB(DATE_SUB(CURDATE(), 1 - DAY(CURDATE())), INTERVAL 1 MONTH)

What is this doing? First, it is only applying functions to the current date part of the expression. This allows MySQL to use an index on date_created , if available and appropriate.

The expression DATE_SUB(CURDATE(), 1 - DAY(CURDATE()) is simply a way to get the first day of the month.

You query have an error, correct one would be:

SELECT * FROM table
WHERE MONTH(date_created) = MONTH(DATE_SUB(NOW(),INTERVAL 2 MONTH))

For current month just MONTH(NOW()), replace "2" with any number of months you need (1,3,.. 23)

as mentioned in comments this solution ignores YEAR differences, it just selects all records with the same month, no matter the year

you can filter wrong year results with additional clause:

 AND YEAR(date_created) = '2019' # or year you need

Or use more complex query:

SELECT * FROM table
where
date_created between
/* first day of -2 month*/
date_sub(date_sub(now(),interval 2 month), interval (day(now())-1) day) 
and
/* last day of -2 month*/
last_day(date_sub(now(),interval 2 month))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM