mysql中的distinct和group by

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xjh163/article/details/96474390
  • 在使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录

我们创建一个表来测试一下:

CREATE table `c_s_s`(
`id` int(11) not null auto_increment,
`country` varchar(20) DEFAULT null,
`sex` varchar(10) DEFAULT null,
`population` int(20) DEFAULT null,
PRIMARY key (`id`),
key `country`(`country`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

insert into `c_s_s`(`country`,`sex`,`population`)
values
('中国',1,360),
('中国',2,240),
('法国',1,300),
('法国',2,300),
('日本',1,200),
('日本',2,50);

用distinct来返回不重复的用户名:

select distinct country
from c_s_s;
  • 但是当我们想同时返回多个关键字时,就会出现错误.比如我们想返回country和sex,并对country去重
select distinct country,sex
from c_s_s

我们看到结果又出现了country的重复字段,为什么呢?

因为当我们使用distinct country,sex,这时的mysql 会认为要过滤掉country,sex两个字段都重复的记录,即distinct对其后面的所有列名都起作用,那我们只distinct和对应的列名放在最后不就行了吗?

把sql这样写:

select sex,distinct country from c_s_s;

但是,这样mysql会报错,因为distinct必须放在要查询字段的开头

  • 所以一般distinct用来查询不重复记录的条数,即
count(distinct col_name)
  • 如果要查询不重复的记录,有时我们可以用group by :
select sex, country from c_s_s
group by country;

但是会有个弊端,有分组函数,没有聚合函数的情况下,mysql会自动返回每个组对应的第一条记录,而舍弃该组的其他记录。
所以要结合具体场景使用

猜你喜欢

转载自blog.csdn.net/xjh163/article/details/96474390