简体   繁体   中英

Get records from current month and next month

I have a events table and each event has a date, the date that is stored in the table is a php time() stamp. I need to list the events but I only want to list the current months events and next months events.

This is the current SQL query I have

    SELECT event_id, event_name, event_date
    FROM events
    ORDER BY event_date DESC

Use Month and Year Function

SELECT event_id, event_name, event_date
FROM events
where Month(event_date) in (month(now()),month(now())+1)
And Year(event_date) = Year(Now())
ORDER BY event_date DESC

If you want to use an index, then do all the transformations on the current date:

where event_date >= date_sub(curdate(), interval day(curdate()) - 1 day) and
      event_date < date_add(date_sub(curdate(), interval day(curdate()) - 1 day), interval 2 month)

MySQL can then use an index (if one exists) on event_date .

This is the answer that works, it took some messing around but it works

    select *
      from events
     where DATE_FORMAT(FROM_UNIXTIME(event_date), '%Y-%m-%d') BETWEEN '2015-08-01' AND '2015-09-01' + INTERVAL 1 MONTH + INTERVAL -1 SECOND
     order by event_date desc

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