[英]Correct MySQL Index for this Simple Query
I have a simple query that does a group by and order by (with a join), but it doesn't seem to be working without temporary tables, and filesort. 我有一个简单的查询,该查询按连接进行分组和排序(使用连接),但是如果没有临时表和文件排序,它似乎无法正常工作。 Here is the query: 这是查询:
SELECT items.name, max(activity.created_at), count(items.item_id) as total_count
FROM activity
INNER JOIN items ON activity.item_id = items.item_id
WHERE activity.user_id = 'XXX'
GROUP BY activity.item_id
order by activity.created_at desc
LIMIT 0, 15
I have an index on: 我有一个索引:
(activity.item_id, activity.user_id, activity.created_at) - idx_item_created
(activity.user_id, activity.created_at) - user_id_2
When I force idx_item_created it does a full table scan, by default it runs using user_id_2 and always produces: 当我强制idx_item_created进行全表扫描时,默认情况下它使用user_id_2运行并始终产生:
Using where; Using temporary; Using filesort
Anyway to optimize this query better? 无论如何优化此查询更好?
You are going to have to have a filesort on this, because you have group by
and order by
with two different expressions. 您将必须对此group by
order by
,因为您需要使用两个不同的表达式进行group by
和order by
。 For this query: 对于此查询:
SELECT items.name, max(activity.created_at), count(items.item_id) as total_count
FROM activity INNER JOIN
items
ON activity.item_id = items.item_id
WHERE activity.user_id = 'XXX'
GROUP BY activity.item_id
order by activity.created_at desc
LIMIT 0, 15
The best index is a covering index on activity
: activity(user_id, item_id, created_at)
. 最好的索引是activity
的覆盖索引: activity(user_id, item_id, created_at)
。 This will not eliminate the file sort, though. 但是,这不会消除文件排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.