我有一个简单的查询,它执行分组依据(带连接),但它似乎没有临时表和filesort。这是查询:
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
我有一个索引:
(activity.item_id, activity.user_id, activity.created_at) - idx_item_created
(activity.user_id, activity.created_at) - user_id_2
当我强制执行idx_item_created时,它执行全表扫描,默认情况下它使用user_id_2运行并始终生成:
Using where; Using temporary; Using filesort
无论如何要更好地优化这个查询?
答案 0 :(得分:0)
您必须拥有此文件,因为您有group by
和order by
两个不同的表达式。对于此查询:
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
最佳索引是activity
上的覆盖索引:activity(user_id, item_id, created_at)
。但这并不会消除文件排序。