mysql优化group by语句性能实例

发布时间:2019-11-18编辑:脚本学堂
本文介绍了mysql性能优化中有关group by语句优化的方法,group by子句会扫描整个表并创建一个新的临时表,表中每个组的所有行应为连续的,然后使用该临时表来找到组并应用累积函数,可优化的空间很大。

执行group by子句的最一般的方法:先扫描整个表,然后创建一个新的临时表,表中每个组的所有行应为连续的,最后使用该临时表来找到组并应用聚集函数(如果有聚集函数)。在某些情况中,mysql通过访问索引就可以得到结果,而不用创建临时表。此类查询的 explain 输出显示 extra列的值为 using index for group-by。

一、松散索引扫描
1、满足条件
查询针对一个表。
group by 使用索引的最左前缀。
只可以使用min()和max()聚集函数,并且它们均指向相同的列。
2、例子
 

复制代码 代码示例:
表t1(c1,c2,c3,c4) 有一个索引 idx(c1,c2,c3):
select c1, c2 from t1 group by c1, c2;
select distinct c1, c2 from t1;
select c1, min(c2) from t1 group by c1;
select c1, c2 from t1 where c1 < const group by c1, c2;
select max(c3), min(c3), c1, c2 from t1 where c2 > const group by c1, c2;
select c2 from t1 where c1 < const group by c1, c2;
select c1, c2 from t1 where c3 = const group by c1, c2;

不满足条件示例:
1,除了min()或max(),还有其它累积函数,例如:
 

复制代码 代码示例:
select c1, sum(c2) from t1 group by c1;

2,group by子句中的域不引用索引开头,例如:
 

复制代码 代码示例:
select c1,c2 from t1 group by c2, c3;

3,查询引用了group by 部分后面的关键字的一部分,并且没有等于常量的等式,例如: 
 

复制代码 代码示例:
select c1,c3 from t1 group by c1, c2;

二、紧凑索引扫描
如果不满足松散索引扫描条件,执行group by仍然可以不用创建临时表。如果where子句中有范围条件,该方法只读取满足这些条件的关键字。
否则,进行索引扫描。该方法读取由where子句定义的范围。
1、group by 中有一个漏洞,但已经由条件c2 = 'a'覆盖。
 

复制代码 代码示例:
select c1,c2,c3 from t1 where c2 = 'a' group by c1,c3;

2、group by 不是满足最左前缀,但是有一个条件提供该元素的常量:
 

复制代码 代码示例:
select c1,c2,c3 from t1 where c1 = 'a' group by c2,c3;