区别
相同点
两者皆可去重
在使用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;
select country
from c_s_s
group by country
;
不同点
group by 可做聚合
select country,sum(population) as total_num
from c_s_s
group by country
;
性能差异
当distinct 和group by 用作去重时,group by的效率比较高