[英]'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.
为简化起见,此查询将联接到另一个表,但是我仅显示max和min查询。
SELECT mv . * , mu . *
FROM (
SELECT Device_id, MAX( Last_time ) AS last_visit,
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. 如果执行解释,它表示此“首次连接”使用的是临时文件排序,这将使数据库在此时崩溃,使用近100%的CPU一段时间。
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? 您在设备跟踪器上的(device_id,Last_time)上有索引吗? And also (Device_id,refferal,Last_time).
还有(Device_id,refferal,Last_time)。
Indexes and GROUP BY can have some rather intricate problems. 索引和GROUP BY可能会有一些相当复杂的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.