mysql去重(过滤重复的记录) distinct 用法

2021-08-2109:20:42数据库教程Comments1,482 views字数 485阅读模式

使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段,例如有如下表user:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

mysql去重(过滤重复的记录) distinct 用法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

用distinct来返回不重复的用户名:select distinct name from user;,结果为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

mysql去重(过滤重复的记录) distinct 用法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

这样只把不重复的用户名查询出来了,但是用户的id,并没有被查询出来:select distinct name,id from user;,这样的结果为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

mysql去重(过滤重复的记录) distinct 用法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

distinct name,id 这样的mysql 会认为要过滤掉name和id两个字段都重复的记录,如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

所以一般distinct用来查询不重复记录的条数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

如果要查询不重复的记录,有时候可以用group by :文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

select id,name from user group by name;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/22250.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/sjk/22250.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定