mysql去重的最方便的两种方法

方法一:     mysql

在使用mysql时,有时须要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但每每只用它来返回不重复记录的条数,而不是用它来返回不重记录的全部值。其缘由是 distinct只能返回它的目标字段,而没法返回其它字段sql

下面先来看看例子:spa

     table
   id name
   1 a
   2 b
   3 c
   4 c
   5 b.net

库结构大概这样,这只是一个简单的例子,实际状况会复杂得多。orm

好比我想用一条语句查询获得name不重复的全部数据,那就必须使用distinct去掉多余的重复记录。blog

select distinct name from table
获得的结果是:get

   name
   a
   b
   cit

好像达到效果了,但是,我想要获得的是id值呢?改一下查询语句吧:io

select distinct name, id from tabletable

结果会是:

   id name
   1 a
   2 b
   3 c
   4 c
   5 b

distinct怎么没起做用?做用是起了的,不过他同时做用了两个字段,也就是必须得id与name都相同的才会被排除。。。。。。。

咱们再改改查询语句:

select id, distinct name from table

很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。。。。。。。

最终好用的语句以下:

select *, count(distinct name) from table group by name

结果:

   id name count(distinct name)
   1 a 1
   2 b 1
   3 c 1

最后一项是多余的,不用管就好了,目的达到。。。。。

哦,对,再顺便说一句,group by 必须放在 order by 和 limit以前,否则会报错。。。。。。。。!OK了

总结语句:select *, count(distinct name) from (select * from table……等嵌套语句) group by name

方法二:

利用group by

[sql] view plaincopy

  1. SELECT * FROM(  

  2. select * from customer where user=(  

  3.     SELECT source_user from customer WHERE user='admin'UNION ALL select * from customer where user=(  

  4.     select source_user from customer where user=(  

  5.         SELECT source_user from customer WHERE user='admin')) union ALL select * from customer where user=(  

  6.     select source_user from customer where user=(  

  7.         select source_user from customer where user=(  

  8.             SELECT source_user from customer WHERE user='admin'))) UNION ALL select * from customer where source_user=(/*个人上线的上线的user*/  

  9.     select user from customer where user=(  

  10.         select source_user from customer where user=(  

  11.             SELECT source_user from customer WHERE user='admin'))) union all select * from customer where source_user=(/*个人上线的上线的上线user*/  

  12.     select user from customer where user=(  

  13.     select source_user from customer where user=(  

  14.         select source_user from customer where user=(  

  15.             SELECT source_user from customer WHERE user='admin'))))) as alias group by user;  

注意加别名,否则报错,注意在where语句外面包装一下,再用group by去重才会生效。

相关文章
相关标签/搜索