开发者

'using temporary' with max and min queries in mysql

I have a big issue with a query in which I need to retrieve some max and min values related to each row. To simplify, this query is being joined to another table, but I'll only show the max and min queries.

SELECT mv . * , mu . * 
FROM (

    SELECT Device_id, MAX( Last_time ) AS last_visit, 
开发者_StackOverflow中文版                      MIN( Last_time ) AS first_visit
    FROM device_tracker
    GROUP BY Device_id
)mv
JOIN (
    SELECT Referral AS current_url, 
    Device_id, MAX( Last_time ) AS last_url_visit, MIN(Last_time ) AS first_url_visit
    FROM device_tracker GROUP BY Device_id, current_url) mu 
ON ( mv.Device_id = mu.Device_id )

If I execute an explain, it says that this 'first join' is using a temporary and filesort, and this makes the database to collapse in this point, using almost a 100% CPU for a while.

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    7275     
1   PRIMARY <derived3>  ALL NULL    NULL    NULL    NULL    15137   Using where
3   DERIVED device_tracker  index   NULL    index_api   522 NULL    28392   Using index; Using temporary; Using filesort
2   DERIVED device_tracker  range   NULL    index_api   257 NULL    7099    Using index for group-by

question: is there any way to force this query to use an index to avoid the the temporary and filesort? Thanks in advance!!!

EDIT: Problem is more focused now. If we execute just the second subquery:

EXPLAIN SELECT Referral, Device_id, MAX( Last_time ), MIN( Last_time )
FROM device_tracker
GROUP BY Device_id, Referral

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  device_tracker  index   NULL    index_api   522 NULL    28412   Using index; Using temporary; Using filesort

and we have set these indexes:

NAME:      TYPE:     ROWS:  FIELDS:
PRIMARY    PRIMARY   28413  id
index_api  INDEX     28413  Device_id, Last_Time, Referral


Do you have an index on (device_id,Last_time) on device tracker? And also (Device_id,refferal,Last_time).

Indexes and GROUP BY can have some rather intricate problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜