dreza
dreza

Reputation: 3645

Optimizing this mysql query to make use of my indexes if possible?

I have a mysql query that I thought should be using my indexes but still seems to be needing to scan alot of rows (I think).

Here is my query:

SELECT DISTINCT DAY(broadcast_at) AS 'days' 
from v3211062009 
where month(broadcast_at) = 5 and 
year(broadcast_at) = 2012 
and deviceid = 337 order by days;

On my table I have an index setup on broadcast_at, deviceid. However the results of a explain on this query looks like:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  v3211062009 ref indx_deviceid,indx_tracking_query   indx_tracking_query 4   const   **172958**  Using where; Using index; Using temporary; Using filesort

I don't understand why it needs to look up so many of the rows. The total amount of rows for this deviceid record is only 184085 so my query seems to be almost looking at all of them just to get the result set. Is the index on broadcast_at not working.

I'm obviously doing something fundamentally wrong but can't figure it out. Changing the order of the columns in my index didn't work.

Upvotes: 3

Views: 52

Answers (1)

Alnitak
Alnitak

Reputation: 340055

I don't think MySQL can take advantage of the index on broadcast_at if you use functions on that field.

How does it perform if you do:

SELECT DISTINCT DAY(broadcast_at) AS 'days' 
from v3211062009 
where broadcast_at >= ('2012-05-01') AND
      broadcast_at < ('2012-06-01') 
and deviceid = 337 order by days;

Upvotes: 4

Related Questions