当前位置:网站首页>MySQL 原理与优化,Group By 优化 技巧
MySQL 原理与优化,Group By 优化 技巧
2022-08-08 23:14:00 【InfoQ】

今天来看看MySQL 中如何多Group By 语句进行优化的。
先创建tb_user 表如下

通过show index from tb_user; 命令查看表,没有存在任何的索引。

执行如下代码,查看SQL 执行情况
explain select profession, count(*) from tb_user group by profession ;

发现返回结果中 type 为“ALL” ,Extra 返回“Using temporary” 说明没有使用索引。
于是,创建基于profession,age和status 的索引如下
create index index_user_pro_age_sta on tb_user(profession ,age, status);
这里创建索引从左到右的顺序是 profession ,age, status。
此时再次执行SQL执行计划如下:
explain select profession, count(*) from tb_user group by profession ;

发现使用了索引“index_user_pro_age_sta”。说明在执行 group by操作的时候,使用联合索引是有效的。
接着在看使用如下代码:
explain select age, count(*) from tb_user group by age;
SQL 语句使用age 进行group by,查看explain的结果如下:

在Extra 字段中发现使用了“Using temporary”,说明没有走索引,是因为没有满足索引的
最左前缀法则
。
联合索引 index_user_pro_age_sta的顺序从左到右分别是 profession ,age, status。
上面的SQL 语句Group by 后面接着的是age ,因此出现“Using temporary”。
这里对SQL 进行修改。如下:
explain select profession,age, count(*) from tb_user group by profession, age;

由于group by 后面跟着profession, age ,符合联合索引的创建顺序,因此索引生效。
我们再来试试再加入过滤条件的情况,加入profession = 软件工程,此时group by 里面只显示 age,那么此时是否会走索引, 答案是 using index。因为满足了最左前缀法则。
explain select age, count(*) from tb_user where profession = '软件工程' group by age;

总结一下:
SQL在分组操作的时候,可以通过索引来提高效率。
做分组操作的时候,索引的使用需要满足最左前缀法则。
边栏推荐
- Manacher(求解最长回文子串)
- Share | design based on MCU P0 mouth to drive the LED flashing
- PHP 正则给img的src添加域名
- makefile automatically compiles C files in directories and subdirectories
- 加载 已训练模型 张量的 几种方法
- 如何搭建一套自己公司的知识共享平台
- Small program figure display banner
- wps a列不见了怎么办?wps a列不见了的解决方法
- Kubernetes资源编排系列之四: CRD+Operator篇
- (2022牛客多校四)N-Particle Arts(思维)
猜你喜欢
随机推荐
CTF Attack and Defense World
STM8L 液晶数码管驱动,温度计液晶屏显示
WeChat small program "decompiled" combat "behind to unpack the eggs
Kubernetes与OpenStack
[PP-YOLOv2] Test a custom dataset
Qt入门(四)——连续播放图片(两种定时器的运用)
Virtualization type (with picture)
PMP考点有哪些啊?
ndk和JNI的使用初探
小程序banner图展示
抽象内部类
(nowcoder22529C)dinner(容斥原理+排列组合)
WeChat applet error undefined Expecting 'STRING','NUMBER','NULL','TRUE','FALSE','{','[', got ]Solution
Python object-oriented
Hand-written prometheus exporter-01-Gauge (dashboard)
(2022牛客多校三)J-Journey(dijkstra)
机器学习之知识点(一)
从洞察到决策,一文解读标签画像体系建设方法论丨DTVision分析洞察篇
MPLS Virtual Private Network Everywhere in Life
(2022牛客多校二)L-Link with Level Editor I(动态规划)








