当前位置:网站首页>MySQL principle and optimization of Group By optimization techniques
MySQL principle and optimization of Group By optimization techniques
2022-08-09 13:03:00 【51CTO】
今天来看看MySQL how muchGroup By 语句进行优化的.
先创建tb_user 表如下
通过show index from tb_user; 命令查看表,No index exists.
执行如下代码,查看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);
Here the order of creating indexes from left to right is profession ,age, status.
此时再次执行SQL执行计划如下:
explain select profession, count(*) from tb_user group by profession ;
found that the index was used“index_user_pro_age_sta”.说明在执行 group by操作的时候,Using a federated index is valid.
Then look at using the following code:
explain select age, count(*) from tb_user group by age;
SQL 语句使用age 进行group by,查看explain的结果如下:
在Extra Field found used“Using temporary”,说明没有走索引,It is because the index is not satisfied最左前缀法则.
联合索引 index_user_pro_age_staThe order is from left to right respectively 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 ,Consistent with the order in which the federated index was created,So the index works.
Let's try again and add the filter condition,加入profession = 软件工程,此时group by 里面只显示 age,Then whether the index will be taken at this time, 答案是 using index.Because the leftmost prefix rule is satisfied.
explain select age, count(*) from tb_user where profession = '软件工程' group by age;
总结一下:
SQLwhen operating in groups,可以通过索引来提高效率.
When doing group operations,The use of indexes needs to satisfy the leftmost prefix rule.
边栏推荐
猜你喜欢
Shell正则表达式,三剑客之grep命令
一甲子,正青春,CCF创建六十周年庆典在苏州举行
【Untitled】
用皮肤“听”音乐,网友戴上这款装备听音乐会:仿佛住在钢琴里
GPT-3组合DALL·E,60秒内搞定游戏设定和原型动画!网友看后:这游戏想玩
太卷了... 腾讯一面被问到内存满了,会发生什么?
超越CLIP的多模态模型,只需不到1%的训练数据!南加大最新研究来了
LeetCode #101. 对称二叉树
[Interview high-frequency questions] Linked list high-frequency questions that can be gradually optimized
The latest interview summary in 20022 brought by Ali senior engineer is too fragrant
随机推荐
Blocking, non-blocking, multiplexing, synchronous, asynchronous, BIO, NIO, AIO all in one pot
[Interview high-frequency questions] Linked list high-frequency questions that can be gradually optimized
曲鸟全栈UI自动化教学(八):框架代码讲解和进一步优化
微信小程序支付及退款整体流程
又有大厂员工连续加班倒下/ 百度搜狗取消快照/ 马斯克生父不为他骄傲...今日更多新鲜事在此...
Apexsqlrecover cannot connect to database
听声辨物,这是AI视觉该干的???|ECCV 2022
【面试高频题】可逐步优化的链表高频题
C# Get system installed .NET version
曼城推出可检测情绪的智能围巾,把球迷给整迷惑了
Apexsqlrecover无法连接数据库
Scala 高阶(七):集合内容汇总(上篇)
PM2之配置文件
获取url地址中问号后参数(即使是iframe也可以)
ABAP 面试题:如何使用 ABAP 编程语言的 System CALL 接口,直接执行 ABAP 服务器所在操作系统的 shell 命令?
ThreadLocal的简单理解
redis库没法引入
字符串 | 反转字符串 | 双指针法 | leecode刷题笔记
AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
李开复花上千万投的缝纫机器人,团队出自大疆