当前位置:网站首页>MySQL 原理与优化,Group By 优化 技巧
MySQL 原理与优化,Group By 优化 技巧
2022-08-09 11:58:00 【51CTO】
今天来看看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在分组操作的时候,可以通过索引来提高效率。
做分组操作的时候,索引的使用需要满足最左前缀法则。
边栏推荐
- WeChat payment development process
- Reading and writing after separation, performance were up 100%
- 字符串 | 反转字符串 | 双指针法 | leecode刷题笔记
- 二重指针-char **、int **的作用
- IDEA close/open reference prompt Usages
- _main C:/ti/ccs1011/ccs/tools/compiler/ti-cgt-c2000_20.2.1.LTS/lib/rts2800_fpu32.lib<ar在线升级跳转疑问
- 微信支付开发流程
- goalng-sync/atomic原子操作
- mysql + redis + flask + flask-sqlalchemy + flask-session 配置及项目打包移植部署
- 2022 Niu Ke Duo School (6) M. Z-Game on grid
猜你喜欢
人体解析(Human Parse)开源数据集整理
二重指针-char **、int **的作用
Programmer's Exclusive Romance - Use 3D Engine to Realize Fireworks in 5 Minutes
【Adobe Premiere Pro 2020】pr2020安装和基本操作【PR安装、新建项目流程、导入及管理素材项目文件、添加标记、创建出入点剪辑视频、快速剪接及自动音乐卡点的方法
Nature:猪死亡1小时后,器官再次运转
非科班AI小哥火了:他没有ML学位,却拿到DeepMind的offer
《数字经济全景白皮书》银行业智能营销应用专题分析 发布
箭头函数和普通函数的常见区别
软件测试——金融测试类面试题,看完直接去面试了
JD.com architects tidy up: what are the core technical knowledge points of jvm and performance tuning
随机推荐
Information system project managers must memorize the core test sites (63) The main process of project portfolio management & DIPP analysis
Redis高可用部署
PM2之配置文件
二重指针-char **、int **的作用
LeetCode热题(11.合并两个有序链表)
ACM01 Backpack problem
字节秋招二面把我干懵了,问我SYN报文什么情况下会被丢弃?
LeetCode_单调栈_中等_456.132 模式
matlab simulink的scope 示波器光标如何移动记录
预置第三方apk到MTK项目相关问题总结
【概率论】正态分布的由来——从大一同学的视角出发
proto3-2 syntax
阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端
TI的片上固化好的boot ROM(上电引导加载程序)退出后的去向
WPF implements a MessageBox message prompt box with a mask
发明时代,「幂集创新」事关你我
拍频造成的轻微震荡
Shell之常用小工具(sort、uniq、tr、cut)
JS 封装节流(后期优化)
win10 outlook邮件设置