苗火 Nicholas
[MySQL]SQL中distinct的用法
2015-12-11 萧
SQL中distinct的用法

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



表A:

































id

name

1

a

2

b

3

c

4

c

5

b

1

a





示例1



select distinct name from A

执行后结果如下:

















name

a

b

c





示例2



select distinct name, id from A

执行后结果如下:





























name

id

a

1

b

2

b

5

c

3

c

4







实际上是根据“name+id”来去重,distinct同时作用在了name和id上,这种方式Access和SQL Server同时支持。



示例3:统计



select count(distinct name) from A;  --表中name去重后的数目, SQL Server支持,而Access不支持

select count(distinct name, id) from A;  --SQL Server和Access都不支持

示例4



select id, distinct name from A;   --会提示错误,因为distinct必须放在开头

其他



distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。

但可以通过其他方法实现。
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容