Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用GROUPBY进行慢速查询_Mysql_Group By_Indexing_Performance - Fatal编程技术网

Mysql 使用GROUPBY进行慢速查询

Mysql 使用GROUPBY进行慢速查询,mysql,group-by,indexing,performance,Mysql,Group By,Indexing,Performance,当我运行以下查询时,速度会变慢(~6秒): SELECT sql_no_cache t1.id, t2.id, count(injury.id) FROM age_group as t1 CROSS JOIN body_part as t2 LEFT JOIN injury ON t1.id = injury.age_group_id AND t2.id = injury.body_part_id GROUP BY t1.id,t2.id 如果我删除分组依据,则

当我运行以下查询时,速度会变慢(~6秒):

SELECT sql_no_cache
    t1.id, t2.id, count(injury.id)
FROM age_group as t1
CROSS JOIN body_part as t2
LEFT JOIN injury 
     ON t1.id = injury.age_group_id 
     AND t2.id = injury.body_part_id
GROUP BY t1.id,t2.id
如果我删除
分组依据
,则它会快速执行

当我使用
EXPLAIN
时,唯一的区别在于
groupby
列出了“使用索引;使用临时;使用文件排序”

我不知道如何避免这种情况

我们需要能够对伤害表中的任何字段进行分组,因此为每个组合编制索引可能不是一个好的解决方案


有什么想法吗?

您可以在不加入的情况下进行聚合:

select injury.age_group_id, injury.body_part_id, count(*)
from injury
group by injury.age_group_id, injury.body_part_id
这只会在有受伤的情况下返回结果

如果执行得很好,则随后执行连接:

select t.id, t2.id, coalesce(injury.cnt, 0)
from age_group as t1 CROSS JOIN
     body_part as t2 left outer join
     (select injury.age_group_id, injury.body_part_id, count(*) as cnt
      from injury
      group by injury.age_group_id, injury.body_part_id
     ) injury LEFT JOIN
     injury ON t1.id = injury.age_group_id and t2.id = injury.body_part_id

你的答案是正确的,但我不确定为什么它更快。解释仍然显示“使用临时;使用文件排序”,这是我对查询速度慢的原因的理解。我认为这是因为结果表只有三列,但若将其更改为包含所有列,但速度仍然一样快。@user2449882。我认为原因是因为它在加入之前进行聚合,所以数据量较小。