sql distinctt group by 分析

本文介绍了SQL中的DISTINCT关键字,展示了如何使用它来选择唯一的不同值。通过多个示例,包括SELECT DISTINCT、COUNT(DISTINCT)及与GROUP BY的比较,帮助读者理解其用法和性能考量。
在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。

示例1
select distinct name from A
示例2

select distinct name, id from A

[color=red]实际上是根据“name+id”来去重,distinct同时作用在了name和id上[/color]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值