mysql - How to optimize SQL query? Keys are not being used -
how can optimize following query? have tried create indexes (idx_events, idx_events_startdate, don't help. query takes 10s far much.
.... 131 rows in set (10.25 sec) mysql> explain select results.event results inner join events on results.event=events.id (datediff(now(), events.startdate) < 30) , (datediff(now(), events.startdate) > -1) , results.status='ok' group events.id; +----+-------------+---------+--------+----------------------------------------------+------------+---------+-----------------------+--------+---------------------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | | +----+-------------+---------+--------+----------------------------------------------+------------+---------+-----------------------+--------+---------------------------------------------------------------------+ | 1 | simple | results | ref | idx_event,idx_status | idx_status | 53 | const | 773425 | using index condition; using where; using temporary; using filesort | | 1 | simple | events | eq_ref | primary,idx_events_name,idx_events_startdate | primary | 4 | eventor.results.event | 1 | using | +----+-------------+---------+--------+----------------------------------------------+------------+---------+-----------------------+--------+---------------------------------------------------------------------+ 2 rows in set (0.01 sec)
wrapping indexed column in function prevents optimiser using it. looks need free index on startdate nice filtered result set join:
select r.event results join events e on e.id = r.event , e.startdate > curdate() - interval 30 day , e.startdate < curdate() + interval 1 day r.status = 'ok'
i placing joined table conditions in on clause , using table aliases possible.
i'd prefer integer status column string 'ok', can foreign key status table description if need it.
as added aside.. use >=
, <
date ranges, if example, startdate
datetime
or timestamp
, query exclude values 2014-08-01 00:00:00
if on cut off of curdate() - interval 30 day
.
Comments
Post a Comment