bitscn.com
mysql group by 操作的优化
默认情况下, mysql 在执行 group by col1 , col2.... 操作的时候,会按照 group by 字段的顺序进行排序。如果显式包括一个包含相同的列的 order by 子句,则对 mysql 的实际执行性能没有什么额外的影响。
如果查询包括 group by 操作, 但是不需要对结果进行排序,或者对默认的排序结果不满意,希望获得结果后再由程序进一步处理的时候,可以指定 order by null 禁止排序,从而避免排序结果的消耗。
下面介绍的例子对比了开启 / 关闭 group by 排序的执行计划:
mysql> desc select dep,pos,avg(sal) from employee group by dep,pos g
*************************** 1. row ***************************
id: 1
select_type: simple
table: employee
type: all
possible_keys: null
key: null
key_len: null
ref: null
rows: 10
extra: using temporary; using filesort
1 row in set (0.00 sec)
mysql> desc select dep,pos,avg(sal) from employee group by dep,pos order by null g
*************************** 1. row ***************************
id: 1
select_type: simple
table: employee
type: all
possible_keys: null
key: null
key_len: null
ref: null
rows: 10
extra: using temporary
1 row in set (0.00 sec)
从执行计划可以看到,使用了 order by null 的 sql 减少了文件排序的步骤,当返回结果集很大时,对于 group by 的性能是有很大改善的。
bitscn.com