简体   繁体   中英

MySQL select complete last month

How to select all data from last month (or 30 days)?

I already found some answers, and mostly gives this solution

SELECT * 
FROM gigs
WHERE date > DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
ORDER BY date DESC

But this gives me also the dates from the future

I am only interested in the days from last month or 30 days (not next month and beyond)

Is this what you want?

WHERE date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND date <= CURRENT_DATE

I added a condition so the query filters on date not greater than today. I also modified your code so the date range starts one month ago (you had 3 months).

try this code

SELECT * FROM gigs
WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
ORDER BY date DESC

You are asking for two separate things.

The last 30 days is easy.

date between now() - interval 30 day and now()

Data this month is like this:

date between (last_day(Now() - INTERVAL 1 MONTH) + INTERVAL 1 DAY) and last_day(Now())

Data a few months ago is like this:

date between (last_day(Now() - INTERVAL 4 MONTH) + INTERVAL 1 DAY) 
       and  
             (last_day(Now() - INTERVAL 3 MONTH) + INTERVAL 1 DAY) 

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