图解 MySQL distinct 调优原理

|

在大多数情况下,DISTINCT[1]可以考虑为GROUP BY的一个特殊案例,如下两个SQL是等效的:

1
2
3
select distinct a, b, c from t30;

select a, b, c from t30 group by a, b, c order by null;

这两个SQL的执行计划如下:

image-20200623224533837

由于这种等效性,适用于Group by的查询优化也适用于DISTINCT。

**区别:**distinct是在group by之后的每组中取出一条记录,distinct分组之后不进行排序。

1、Extra中的distinct

在一个关联查询中,如果您只是查询驱动表的列,并且在驱动表的列中声明了distinct关键字,那么优化器会进行优化,在被驱动表中查找到匹配的第一行时,将停止继续扫描。如下SQL:

1
explain select distinct t30.a  from t30, t31 where t30.c=t30.c;

执行计划如下,可以发现Extra列中有一个distinct,该标识即标识用到了这种优化[1:1]

image-20200623231333626

References


  1. 8.2.1.18 DISTINCT Optimization. Retrieved from https://dev.mysql.com/doc/refman/8.0/en/distinct-optimization.html ↩︎ ↩︎