饿虎岗资源网 Design By www.oxmxm.com
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去重才会生效。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
饿虎岗资源网 Design By www.oxmxm.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
饿虎岗资源网 Design By www.oxmxm.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《张国荣 首首动听经典不容错过 追忆的风 2CD》[WAV+CUE][870MB]
- 《腾格尔 容中尔甲 亚东 高原三星 男人篇 3CD》[WAV/分轨][1GB]
- 命运圣契公测实测可用兑换码大全 命运圣契最新兑换码分享
- 黑神话悟空上品疾蝠精魄获取方法一览|上品疾蝠精魄收集攻略
- 《七龙珠电光炸裂!ZERO》GT角色预告片曝光,15位新角色登场
- [ABC]安娜-胆麦发烧女声[6N纯银镀膜][2016[低速原抓WAV+CUE]
- NewViennaOctetViennaWindSoloists-TheDeccaRecordings(2024)18CD[24-48][FLAC]-7
- 雨果唱片-三角琴《俄罗斯民间音乐系列-梁祝(中国名曲)》wav
- 《塞尔达传说:智慧的再现》新实机!无之世界介绍
- 任天堂公布《塞尔达传说》系列时间线:野炊与王泪独立在外
- 任天堂更新网络投稿规范:打击影响他人游戏体验行为
- 冼佩瑾.2024-女儿Daughter(EP)【杰威尔】【FLAC分轨】
- 黑豹乐队.1993-光芒之神【摇音晨【WAV+CUE】
- 曾轶可.2011-一只猫的旅行【天娱传媒】【WAV+CUE】
- 黑神话悟空上品狼刺客精魄获取方法一览|上品狼刺客精魄收集攻略