mysql去重复关键字distinct的用法和distinct去重复失效问题

一、distinct是什么?

distinct是mysql去重复关键字。

二、使用规则

1.distinct关键字必须在select后面第一位

表里所有数据的去重复
select
    distinct comptemplate.*
    from comptemplate
表里所有某个字段的数据去重复
select
    distinct comptemplate.comptemplate_name
    from comptemplate

2.distinct去重复的依据

	distinct去重复的依据是从select到from里的所有字段,
也就是每一行的数据和所有的数据做对比,如果重复则去除掉。

三.去重复失效

1.distinct关键字错误理解的sql使用

 多表关联的错误理解使用,想对comptemplate表的所有重复数据
 去重,查出来的数据如下。
   select
   distinct comptemplate.*,tubetemplate.*
   from comptemplate
   left join extemplate_tube_relation on extemplate_tube_relation.comptemplate_id = comptemplate.comptemplate_id
   left join tubetemplate on extemplate_tube_relation.tubetemplate_id = tubetemplate.tubetemplate_id

在这里插入图片描述

2.distinct关键字正确理解的sql使用

多表关联的正确理解使用,想对comptemplate表的所有重复数据
去重,查出来的数据如下。
   select
   distinct comptemplate.*
   from comptemplate
   left join extemplate_tube_relation on extemplate_tube_relation.comptemplate_id = comptemplate.comptemplate_id
   left join tubetemplate on extemplate_tube_relation.tubetemplate_id = tubetemplate.tubetemplate_id

在这里插入图片描述

3.对比两个使用sql

在select中多了tubetemplate.*,导致无法去重复comptemplate.*。
原因是因为distinct是对一行去重复,也就是select到from里的所有字段,
每一行的数据和所有的数据做对比,如果重复则去除掉。

四.注意

	如果表数据存在空格不一的情况,也是无法去重复的!
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐