当前位置:网站首页>面试突击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面试真题解析
边栏推荐
- 接雨水问题解析
- Is not a drawable (color or path): the vector graph downloaded externally cannot be called when it is put into mipmap, and the calling error program crashes
- LeetCode-1279. Traffic light intersection
- 黑馬--Redis篇
- Synchronous development of business and application: strategic suggestions for application modernization
- [translation] a GPU approach to particle physics
- JDBC details
- Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic
- AIRIOT物联网平台赋能集装箱行业构建【焊接工位信息监控系统】
- R language ggplot2 visualization: use ggviolin function of ggpubr package to visualize violin diagram
猜你喜欢
倒计时2天|腾讯云消息队列数据接入平台(Data Import Platform)直播预告
Solution of intelligent management platform for suppliers in hardware and electromechanical industry: optimize supply chain management and drive enterprise performance growth
第五期个人能力认证考核通过名单公布
Meilu biological IPO was terminated: the annual revenue was 385million, and Chen Lin was the actual controller
Simple understanding of MySQL database
Actf 2022 came to a successful conclusion, and 0ops team won the second consecutive championship!!
打家劫舍III[后序遍历与回溯+动态规划]
Based on butterfly species recognition
PMP practice once a day | don't get lost in the exam -7.6
思维导图+源代码+笔记+项目,字节跳动+京东+360+网易面试题整理
随机推荐
USB host driver - UVC swap
How to improve website weight
R language uses the order function to sort the dataframe data, and descending sorting based on a single field (variable)
Graffiti intelligence is listed on the dual main board in Hong Kong: market value of 11.2 billion Hong Kong, with an annual revenue of 300 million US dollars
R language ggplot2 visualization: use the ggstripchart function of ggpubr package to visualize the grouped dot strip plot, and set the add parameter to add box plots for different levels of dot strip
GCC【7】- 编译检查的是函数的声明,链接检查的是函数的定义bug
Interface test tool - postman
Detailed idea and code implementation of infix expression to suffix expression
short i =1; I=i+1 and short i=1; Difference of i+=1
A popular explanation will help you get started
关于静态类型、动态类型、id、instancetype
Mysql Information Schema 学习(二)--Innodb表
JDBC details
10 schemes to ensure interface data security
学习探索-无缝轮播图
C language daily practice - day 22: Zero foundation learning dynamic planning
全套教学资料,阿里快手拼多多等7家大厂Android面试真题
Wx applet learning notes day01
Swagger2 reports an error illegal DefaultValue null for parameter type integer
usb host 驱动 - UVC 掉包