当前位置:Gxlcms > 数据库问题 > mysql中去重 distinct 用法

mysql中去重 distinct 用法

时间:2021-07-01 10:21:17 帮助过:28人阅读

10 20 30
  • 对多个字段进行去重sql:
select distinct name,age from user;

查询结果
name    age
One    10
Zero    20
Two    20
Four    30
One    30
  • 对多个字段进行去重并求count的sql(实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段):
select count(distinct name,age) as total from user;

查询结果
total
5
  • 对select * 进行去重
select distinct * from user;

由于 * 代表所有字段,所以该sql和 select distinct id,name,age,sign from user 语义相同

查询结果:
id        name    age        sign
1        One        10        梦想要有的,万一实现了呢
2        Zero    20        http://www.chaoshizhushou.com
3        Two        20        OneZeroTwoFour
4        Four    30        加油
5        One        30        学习才是硬道理
6        Four    30        一日三省吾身

 

如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数。

如果要查询不重复的记录,有时候可以用group by :

select id,name from user group by name;

mysql中去重 distinct 用法

标签:mys   多个   学习   sel   sig   one   不重复   div   inf   

人气教程排行