I have a table in my DB something like this:
---------------------------------------------------------- | event_id | date | start_time | end_time | duration | ---------------------------------------------------------- | 1 | 2011-05-13 | 01:00:00 | 04:00:00 | 10800 | | 2 | 2011-05-12 | 17:00:00 | 01:00:00 | 28800 | | 3 | 2011-05-11 | 11:00:00 | 14:00:00 | 10800 | ----------------------------------------------------------
In this example, the data does not give an absolutely accurate picture, usually events cover every hour of every day. The date always refers to start_time, since end_time can sometimes be the next day. Duration in seconds.
SELECT * FROM event_schedules WHERE ( date = CURDATE() //today OR date = DATE_SUB(CURDATE(), INTERVAL 1 DAY) //yesterday ) // and ended before now() AND DATE_ADD(CONCAT(date, ' ', start_time), INTERVAL duration SECOND) < NOW() ORDER BY CONCAT(date, ' ', start_time) DESC LIMIT 1
I have a sentence, an OR'ed clause in brackets, which is optional. I was hoping this could improve the query time by first filtering out any “events” that don't fire today or yesterday. The only way to find the last “event” is to order records first. By adding this extra sentence, am I actually reducing the list of records that need to be ordered? If so, I cannot imagine the optimizer capable of doing this optimization, most of the other issues like this talk about the optimizer.
source share