当前位置:网站首页>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.
边栏推荐
- Experiment record: the process of building a network
- 防止数据冒用的方法
- Go-based web access parameters
- Too much volume... Tencent was asked on the side that the memory was full, what would happen?
- Batch大小不一定是2的n次幂!ML资深学者最新结论
- 【重要】C语言进阶 -- 自定义类型:结构体、枚举、联合
- AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
- ABAP 报表中如何以二进制方式上传本地文件试读版
- 微信支付开发流程
- 微服务架构的核心关键点
猜你喜欢
随机推荐
索引index
MongoDB-查询中$all的用法介绍
【微服务~远程调用】整合RestTemplate、WebClient、Feign
获取url地址中问号后参数(即使是iframe也可以)
GET请求和POST请求区别
字符串 | 反转字符串 | 双指针法 | leecode刷题笔记
PM2之配置文件
ACM01 Backpack problem
微信小程序支付及退款整体流程
WeChat payment development process
OpenSSF的开源软件风险评估工具:Scorecards
Common gadgets of Shell (sort, uniq, tr, cut)
JS 封装节流(后期优化)
《数字经济全景白皮书》银行业智能营销应用专题分析 发布
C# Get system installed .NET version
【重要】C语言进阶 -- 自定义类型:结构体、枚举、联合
Recommend a free 50-hour AI computing platform
【Adobe Premiere Pro 2020】pr2020安装和基本操作【PR安装、新建项目流程、导入及管理素材项目文件、添加标记、创建出入点剪辑视频、快速剪接及自动音乐卡点的方法
win10右键文件,一直转圈
我们真的需要DApp吗?App真的不能满足我们的幻想吗?