Group by 和distinct对比

**  Group by 和distinct对比**

CREATE TABLE sbtest1 (
id int(11) NOT NULL AUTO_INCREMENT,
k int(11) NOT NULL DEFAULT '0',
c char(120) NOT NULL DEFAULT '',
pad char(60) NOT NULL DEFAULT '',
PRIMARY KEY (id),
KEY k_1 (k)
) ENGINE=InnoDB AUTO_INCREMENT=10000001 DEFAULT CHARSET=utf8;
1000w数据量

1、  对于主键

Group by的执行计划
Group by 和distinct对比
Distinct的执行计划
Group by 和distinct对比
可以看到group by使用了主键,而distinct使用了辅助索引k_1
这说明了distinct可能是一种统计操作,也就是Innodb在有辅助索引时候,统计会走辅助索引,如下图,进行count(*)也是走的k_1辅助索引。
Group by 和distinct对比

2、  对于辅助索引

Group by的执行计划
Group by 和distinct对比
Distinct的执行计划
Group by 和distinct对比
通过以上对比,可以看出来他们是等价的,执行计划一致。

3、  对于普通字段

Group by的执行计划,这里做了一个order by null的处理,就是不排序
Group by 和distinct对比
Distinct的执行计划,按理说,如果distinct要是统计的话为啥没有走k_1
Group by 和distinct对比
通过以上对比,可以看出来也是等价的,执行计划一致。

4、  Group by 需要聚合,而distinct不需要聚合

5、  Group by 比 distinct效率高,distinct需要读取所有记录,而group by只需要读取分组的

数量的记录。
set profiling=1;
select distinct(k) from sbtest1
select k from sbtest1 group by k
再通过show profiles查看
Group by 和distinct对比
Group by比distinct快了0.05秒多

猜你喜欢

转载自blog.51cto.com/8370646/2313603