sql 之 distinct

写sql时,要去重,首先想到distinct,但是distinct到底有哪些用法,貌似还不是很清楚,做一下总结。

表a
image

表b
image

作用于单列

select distinct name from A

查询结果如下:
image

作用于多列

select distinct name, id from A

查询结果如下:
image
以name、id两个字段来判断是否重复,但不是把两个字段拼接起来对比。

如执行下面的sql:
select distinct xing, ming from B

查询结果是:
image

作用于多列,但有一列还是希望是单一值

如直接作用于多列的查询结果如下,PLAN NUMBER是有重复的:
image

现在还是想PLAN NUMBER是不重复的,有以下方法:

  • 使用 group_concat 函数
    image

  • 使用group by函数
    image

聚合函数中使用distinct:一般跟 COUNT 结合使用, count()会过滤掉null项

image
实际包含null项有4个记录,执行语句后过滤null项,计算为3。

count是不能统计多个字段的。
如下面的sql是无法运行的:
select count(distinct name, id) from A

若想使用,请使用嵌套查询:
select count(*) from (select distinct xing, name from B) AS M

注意事项

  • distinct 【查询字段】,必须放在要查询字段的开头,即放在第⼀个参数;
  • 只能在SELECT 语句中使⽤,不能在 INSERT, DELETE, UPDATE 中使⽤;
  • distinct 带不带括号效果一样
    image

image

https://blog.csdn.net/shenziheng1/article/details/102536146
https://baijiahao.baidu.com/s?id=1709966309120511971&wfr=spider&for=pc
http://www.javashuo.com/article/p-oiqfewum-dk.html

posted @ 2022-05-14 11:15  捷后愚生  阅读(3062)  评论(0编辑  收藏  举报