登录  /  注册
mysql去重的两种方法实例详解
怪我咯
发布: 2017-07-05 11:08:18
原创
1811人浏览过

这篇文章主要介绍了mysql去重的两种方法详解及实例代码的相关资料,这里对去重的两种方法进行了一一实例详解,需要的朋友可以参考下

mysql去重

方法一:

使用MySQL时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是 distinct只能返回它的目标字段,而无法返回其它字段

下面先来看看例子:

   table
  id name
  1 a
  2 b
  3 c
  4 c
  5 b
登录后复制

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

比如我想用一条语句查询得到name不重复的所有数据,那就必须使用distinct去掉多余的重复记录。

select distinct name from table
登录后复制

得到的结果是:

 name
  a
  b
  c
登录后复制

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

select distinct name, id from table
登录后复制

结果会是:

 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

SELECT * FROM( 
select * from customer where user=( 
  SELECT source_user from customer WHERE user='admin') UNION ALL select * from customer where user=( 
  select source_user from customer where user=( 
    SELECT source_user from customer WHERE user='admin')) union ALL select * from customer where user=( 
  select source_user from customer where user=( 
    select source_user from customer where user=( 
      SELECT source_user from customer WHERE user='admin'))) UNION ALL select * from customer where source_user=(/*我的上线的上线的user*/ 
  select user from customer where user=( 
    select source_user from customer where user=( 
      SELECT source_user from customer WHERE user='admin'))) union all select * from customer where source_user=(/*我的上线的上线的上线user*/ 
  select user from customer where user=( 
  select source_user from customer where user=( 
    select source_user from customer where user=( 
      SELECT source_user from customer WHERE user='admin'))))) as alias group by user;
登录后复制

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

以上就是mysql去重的两种方法实例详解的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学