当前位置:网站首页>面试突击63:MySQL 中如何去重?
面试突击63:MySQL 中如何去重?
2022-07-06 11:32:00 【王磊】
在 MySQL 中,最常见的去重方法有两个:使用 distinct 或使用 group by,那它们有什么区别呢?接下来我们一起来看。
1.创建测试数据
-- 创建测试表
drop table if exists pageview;
create table pageview(
id bigint primary key auto_increment comment '自增主键',
aid bigint not null comment '文章ID',
uid bigint not null comment '(访问)用户ID',
createtime datetime default now() comment '创建时间'
) default charset='utf8mb4';
-- 添加测试数据
insert into pageview(aid,uid) values(1,1);
insert into pageview(aid,uid) values(1,1);
insert into pageview(aid,uid) values(2,1);
insert into pageview(aid,uid) values(2,2);
最终展现效果如下: 
2.distinct 使用
distinct 基本语法如下:
SELECT DISTINCT column_name,column_name FROM table_name;
2.1 单列去重
我们先用 distinct 实现单列去重,根据 aid(文章 ID)去重,具体实现如下: 
2.2 多列去重
除了单列去重之外,distinct 还支持多列(两列及以上)去重,我们根据 aid(文章 ID)和 uid(用户 ID)联合去重,具体实现如下: 
2.3 聚合函数+去重
使用 distinct + 聚合函数去重,计算 aid 去重之后的总条数,具体实现如下: 
3.group by 使用
group by 基础语法如下:
SELECT column_name,column_name FROM table_name
WHERE column_name operator value
GROUP BY column_name
3.1 单列去重
根据 aid(文章 ID)去重,具体实现如下:
与 distinct 相比 group by 可以显示更多的列,而 distinct 只能展示去重的列。
3.2 多列去重
根据 aid(文章 ID)和 uid(用户 ID)联合去重,具体实现如下: 
3.3 聚合函数 + group by
统计每个 aid 的总数量,SQL 实现如下:
从上述结果可以看出,使用 group by 和 distinct 加 count 的查询语义是完全不同的,distinct + count 统计的是去重之后的总数量,而 group by + count 统计的是分组之后的每组数据的总数。
4.distinct 和 group by 的区别
官方文档在描述 distinct 时提到:在大多数情况下 distinct 是特殊的 group by,如下图所示:
官方文档地址:https://dev.mysql.com/doc/refman/8.0/en/distinct-optimization.html 但二者还是有一些细微的不同的,比如以下几个。
区别1:查询结果集不同
当使用 distinct 去重时,查询结果集中只有去重列信息,如下图所示:
当你试图添加非去重字段(查询)时,SQL 会报错如下图所示:
而使用 group by 排序可以查询一个或多个字段,如下图所示: 
区别2:使用业务场景不同
统计去重之后的总数量需要使用 distinct,而统计分组明细,或在分组明细的基础上添加查询条件时,就得使用 group by 了。 使用 distinct 统计某列去重之后的总数量:
统计分组之后数量大于 2 的文章,就要使用 group by 了,如下图所示: 
区别3:性能不同
如果去重的字段有索引,那么 group by 和 distinct 都可以使用索引,此情况它们的性能是相同的;而当去重的字段没有索引时,distinct 的性能就会高于 group by,因为在 MySQL 8.0 之前,group by 有一个隐藏的功能会进行默认的排序,这样就会触发 filesort 从而导致查询性能降低。
总结
大部分场景下 distinct 是特殊的 group by,但二者也有细微的区别,比如它们在查询结果集上、使用的具体业务场景上,以及性能上都是不同的。
参考 & 鸣谢
zhuanlan.zhihu.com/p/384840662
是非审之于己,毁誉听之于人,得失安之于数。
公众号:Java面试真题解析
边栏推荐
- Airiot IOT platform enables the container industry to build [welding station information monitoring system]
- 主从搭建报错:The slave I/O thread stops because master and slave have equal MySQL serv
- Carte de réflexion + code source + notes + projet, saut d'octets + jd + 360 + tri des questions d'entrevue Netease
- ROS custom message publishing subscription example
- R language ggplot2 visualization: use ggviolin function of ggpubr package to visualize violin diagram
- Dark horse -- redis
- Analysis of frequent chain breaks in applications using Druid connection pools
- 凤凰架构2——访问远程服务
- Computer network: sorting out common network interview questions (I)
- Pychrm Community Edition calls matplotlib pyplot. Solution of imshow() function image not popping up
猜你喜欢

倒计时2天|腾讯云消息队列数据接入平台(Data Import Platform)直播预告
Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic

LeetCode-1279. Traffic light intersection
![打家劫舍III[后序遍历与回溯+动态规划]](/img/9b/e9eeed138e46afdeed340bf2629ee1.png)
打家劫舍III[后序遍历与回溯+动态规划]
Interview assault 63: how to remove duplication in MySQL?

ACTF 2022圆满落幕,0ops战队二连冠!!

PMP每日一练 | 考试不迷路-7.6

Druid database connection pool details

思维导图+源代码+笔记+项目,字节跳动+京东+360+网易面试题整理
![[translation] a GPU approach to particle physics](/img/07/57036c925155cab36678c696e89440.jpg)
[translation] a GPU approach to particle physics
随机推荐
Swagger2 reports an error illegal DefaultValue null for parameter type integer
Simple understanding of MySQL database
R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化分组点状条带图(dot strip plot)、设置add参数为不同水平点状条带图添加箱图
Meilu biological IPO was terminated: the annual revenue was 385million, and Chen Lin was the actual controller
PMP practice once a day | don't get lost in the exam -7.6
Interface test tool - postman
Lucun smart sprint technology innovation board: annual revenue of 400million, proposed to raise 700million
ROS custom message publishing subscription example
R语言使用rchisq函数生成符合卡方分布的随机数、使用plot函数可视化符合卡方分布的随机数(Chi Square Distribution)
How word displays modification traces
R语言ggplot2可视化时间序列柱形图:通过双色渐变配色颜色主题可视化时间序列柱形图
The list of people who passed the fifth phase of personal ability certification assessment was published
Excel 中VBA脚本的简单应用
三面蚂蚁金服成功拿到offer,Android开发社招面试经验
Airiot IOT platform enables the container industry to build [welding station information monitoring system]
[translation] a GPU approach to particle physics
Don't miss this underestimated movie because of controversy!
How to improve website weight
助力安全人才专业素养提升 | 个人能力认证考核第一阶段圆满结束!
Pytorch common loss function