0
点赞
收藏
分享

微信扫一扫

sql 之 distinct

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

表a

sql 之 distinct_多列

表b

sql 之 distinct_字段_02

作用于单列

select distinct name from A

查询结果如下:

sql 之 distinct_字段_03

作用于多列

select distinct name, id from A

查询结果如下:

sql 之 distinct_sql_04

以name、id两个字段来判断是否重复,但不是把两个字段拼接起来对比。

如执行下面的sql:

select distinct xing, ming from B

查询结果是:

sql 之 distinct_字段_05

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

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

sql 之 distinct_字段_06

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

  • 使用 group_concat 函数

    sql 之 distinct_多列_07

  • 使用group by函数

    sql 之 distinct_字段_08

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

sql 之 distinct_多列_09

实际包含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 带不带括号效果一样
    sql 之 distinct_字段_10

sql 之 distinct_多列_11


​​https://baijiahao.baidu.com/s?id=1709966309120511971&wfr=spider&for=pc​​

​​http://www.javashuo.com/article/p-oiqfewum-dk.html​​




举报

相关推荐

0 条评论