sql distinctt group by 分析

在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。

示例1
select distinct name from A
示例2

select distinct name, id from A

实际上是根据“name+id”来去重,distinct同时作用在了name和id上

示例3:统计
select count(distinct name) from A;
select count(distinct name, id) from A; mysql 支持的
示例4
select id, distinct name from A;   --会提示错误,因为distinct必须放在开头

网上的一些测试结果;
加了索引之后 distinct 比没加索引的 distinct 快了 107倍。
加了索引之后 group by 比没加索引的 group by 快了 43倍。
再来对比 :distinct  和 group by
不管是加不加索引 group by 都比 distinct 快。因此使用的时候建议选 group by

猜你喜欢

转载自haidaoqi3630.iteye.com/blog/2202310
今日推荐