MySQL - order by和 group by 优化初探

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: MySQL - order by和 group by 优化初探

20200803163208203.png

生猛干货

带你搞定MySQL实战,轻松对应海量业务处理及高并发需求,从容应对大场面试


DB Version

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.28    |
+-----------+
1 row in set
mysql> 


Table

CREATE TABLE `employees` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
  `age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
  `position` varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
  `hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职时间',
  PRIMARY KEY (`id`),
  KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='员工记录表';


两个索引

  1. 主键索引
  2. 二级索引 KEY idx_name_age_position (name,age,position) USING BTREE

重点就是这个二级索引 ,记号了哈。


数据量

mysql> select count(1) from employees ;
+----------+
| count(1) |
+----------+
|   100002 |
+----------+
1 row in set
mysql> 


案例一 :explain select * from employees where name = ‘LiLei’ and position = ‘dev’ order by age

explain select * from employees where name = 'LiLei' and position = 'dev' order by age ;


先想一下这个order by 会不会走索引 ?


20200803201718563.png

会走索引

原因呢 ?

脑海中要有这个联合索引在MySQL底层的B+Tree的数据结构 , 索引 排好序的数据结构。

20200803201443527.png


name = ‘LiLei’ and position = ‘dev’ order by age


name 为 LiLei , name 确定的情况下, age 肯定是有序的 ,age 有序不能保证position 有序


所以 这个order by age 是可以走索引的


继续分析下这个explain

mysql> explain select * from employees where name = 'LiLei' and position = 'dev' order by age ;
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 74      | const |    1 |       10 | Using index condition |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
1 row in set

order by 走的索引 是不会体现在key_len上的, 这个74 = 3 * 24 + 2 , 是计算的name 。 最左匹配原则 ,中间字段不能断,因此查询用到了name索引。


但是 Extra直接里面可以看出来 Using index condition ,说明age索引列用在了排序过程中 。 如果没有走索引的话,那就是 Using FileSort 了


接下来继续看几个例子,加深理解,重点是脑海中的 索引B+Tree结构


案例二: explain select * from employees where name = ‘LiLei’ order by position

mysql> explain select * from employees where  name = 'LiLei' order by position ;     


想一想,这个order by 会走索引吗?


我们来看下索引 KEY idx_name_age_position (name,age,position) USING BTREE


再来看下查询SQL

where  name = 'LiLei' order by position ;

name = LiLei , name 值能确定下来, 符合最左匹配原则 所以查询会走索引 , 用了联合索引中的name字段, key len = 74 . 所以 Using index condition


order by position , 在索引中 中间缺失了age , 用position ,跳过了age , 那索引树能是有序的吗? 肯定不是。。。所以 position肯定不是排好序的 , 无法走索引排序,因此 Extra信息 有 Using filesort


来看下执行计划

mysql> explain select * from employees where  name = 'LiLei' order by position ;     
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref   | rows | filtered | Extra                                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 74      | const |    1 |      100 | Using index condition; Using filesort |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
1 row in set
mysql> 


正如分析~

有感觉了吗? 再来看一个


案例三:explain select * from employees where name = ‘LiLei’ order by age , position


这个SQL和案例二的很相似 , 仅仅在排序的时候在前面多了一个age字段参与排序 , 那分析分析 order by 会走索引吗

mysql> explain select * from employees where  name = 'LiLei' order by age , position ;


时刻不要那个索引树 ,来分析一下


name = LiLei , name 固定,结合 建立的索引, 最左原则,所以查询肯定会走联合索引中的部分索引 name .


在name都是LiLei 的情况下 , order by age , position 结合索引树 ,age和position用于排序 也是有序的,应该不会走using filesort


我们来看下执行计划


20200804100556429.png

mysql> explain select * from employees where  name = 'LiLei' order by age , position ;
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 74      | const |    1 |      100 | Using index condition |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+-----------------------+
1 row in set
mysql> 


案例四:explain select * from employees where name = ‘LiLei’ order by position , age


再分析一个,和案例上也很像。 把 order by的排序顺序 调整一下,我们来分析一下 order by会不会走索引

explain select * from employees where  name = 'LiLei' order by position , age ;   

2020080410094654.png

mysql> explain select * from employees where  name = 'LiLei' order by position , age ;   
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref   | rows | filtered | Extra                                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 74      | const |    1 |      100 | Using index condition; Using filesort |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
1 row in set
mysql> 


咦 , 执行计划中有 using filesort

为什么呢?

看看我们二级索引的建立的字段顺序 , 创建顺序为name,age,position,但是排序的时候age和position颠倒位置了, 那排好序的特性肯定就无法满足了,那你让MySQL怎么走索引?


案例五:explain select * from employees where name = ‘LiLei’ and age = 18 order by position , age ;


这个order by 会走索引吗?

20200804155352325.png

mysql> explain select * from employees where name = 'LiLei' and age = 18 order by position , age ;
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------------+------+----------+-----------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref         | rows | filtered | Extra                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------------+------+----------+-----------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 78      | const,const |    1 |      100 | Using index condition |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------------+------+----------+-----------------------+
1 row in set
mysql> 


走了dx_name_age_position 索引中的 name 和 age , order by 其实也走了索引,你看extra中并没有 using filesort ,因为age为常量,在排序中被MySQL优化了,所以索引未颠倒,不会出现Using filesort


案例六:explain select * from employees where name = ‘LiLei’ order by age asc , position desc ;

mysql> explain select * from employees where name = 'LiLei'  order by  age asc , position desc ;  
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
| id | select_type | table     | partitions | type | possible_keys         | key                   | key_len | ref   | rows | filtered | Extra                                 |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
|  1 | SIMPLE      | employees | NULL       | ref  | idx_name_age_position | idx_name_age_position | 74      | const |    1 |      100 | Using index condition; Using filesort |
+----+-------------+-----------+------------+------+-----------------------+-----------------------+---------+-------+------+----------+---------------------------------------+
1 row in set


20200804155813933.png

我们可以看到虽然排序的字段列与建立索引的顺序一样, order by默认升序排列,而SQL中的 position desc变成了降序排列,导致与索引的排序方式不同,从而产生Using filesort。

Note: Mysql8以上版本有降序索引可以支持该种查询方式。


案例七:explain select * from employees where name in (‘HanMeiMei’ , ‘LiLei’) order by age , position ;

mysql> explain select * from employees where name in ('HanMeiMei' , 'LiLei')  order by  age  , position  ;    
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+------+----------+---------------------------------------+
| id | select_type | table     | partitions | type  | possible_keys         | key                   | key_len | ref  | rows | filtered | Extra                                 |
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+------+----------+---------------------------------------+
|  1 | SIMPLE      | employees | NULL       | range | idx_name_age_position | idx_name_age_position | 74      | NULL |    2 |      100 | Using index condition; Using filesort |
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+------+----------+---------------------------------------+
1 row in set
mysql> 



对order by 来讲 ,多个相等的条件也是 范围查询。 既然是范围查询, 可能对于每个值在索引中是有序的,但多个合并在一起,就不是有序的了,所以 using filesort .


案例八: explain select * from employees where name > ‘HanMeiMei’ order by name ;

mysql> explain select * from employees where name > 'HanMeiMei'  order by  name  ;       
+----+-------------+-----------+------------+------+-----------------------+------+---------+------+-------+----------+-----------------------------+
| id | select_type | table     | partitions | type | possible_keys         | key  | key_len | ref  | rows  | filtered | Extra                       |
+----+-------------+-----------+------------+------+-----------------------+------+---------+------+-------+----------+-----------------------------+
|  1 | SIMPLE      | employees | NULL       | ALL  | idx_name_age_position | NULL | NULL    | NULL | 96845 |       50 | Using where; Using filesort |
+----+-------------+-----------+------------+------+-----------------------+------+---------+------+-------+----------+-----------------------------+
1 row in set
mysql> 


MySQL自己内部有一套优化机制,且数据量不同、版本不一样,结果也可能有差异

一般情况下, 联合索引第一个字段用范围不一定会走索引 , 可以采用 覆盖索引进行优化,避免回表带来的性能开销 。

mysql> explain select name
 from employees where name > 'a'  order by  name  ;       
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+-------+----------+--------------------------+
| id | select_type | table     | partitions | type  | possible_keys         | key                   | key_len | ref  | rows  | filtered | Extra                    |
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+-------+----------+--------------------------+
|  1 | SIMPLE      | employees | NULL       | range | idx_name_age_position | idx_name_age_position | 74      | NULL | 48422 |      100 | Using where; Using index |
+----+-------------+-----------+------------+-------+-----------------------+-----------------------+---------+------+-------+----------+--------------------------+
1 row in set
mysql> 

20200804160859182.png


group by 优化


  • group by与order by类似,其实质是先排序后分组遵照索引创建顺序的最左前缀法则
  • 对于group by的优化如果不需要排序的可以加上order by null禁止排序
  • where高于having,能写在where中的限定条件就不要去having限定了。


小结


MySQL支持两种方式的排序filesort和index,Using index是指MySQL扫描索引本身完成排序


order by满足两种情况会使用Using index

A: order by语句使用索引最左前列。

B: 使用where子句与order by子句条件列组合满足索引最左前列


尽量在索引列上完成排序,遵循索引建立(索引创建的顺序)时的最左前缀法则


如果order by的条件不在索引列上,就会产生Using filesort


能用覆盖索引尽量用覆盖索引


搞定MySQL


https://artisan.blog.csdn.net/article/details/107767649?spm=1001.2014.3001.5502


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。   相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情: https://www.aliyun.com/product/rds/mysql 
相关文章
|
3月前
|
SQL 缓存 关系型数据库
MySQL 慢查询是怎样优化的
本文深入解析了MySQL查询速度变慢的原因及优化策略,涵盖查询缓存、执行流程、SQL优化、执行计划分析(如EXPLAIN)、查询状态查看等内容,帮助开发者快速定位并解决慢查询问题。
137 0
|
24天前
|
缓存 关系型数据库 MySQL
降低MySQL高CPU使用率的优化策略。
通过上述方法不断地迭代改进,在实际操作中需要根据具体场景做出相对合理判断。每一步改进都需谨慎评估其变动可能导致其他方面问题,在做任何变动前建议先在测试环境验证其效果后再部署到生产环境中去。
65 6
|
2月前
|
存储 SQL 关系型数据库
MySQL 核心知识与索引优化全解析
本文系统梳理了 MySQL 的核心知识与索引优化策略。在基础概念部分,阐述了 char 与 varchar 在存储方式和性能上的差异,以及事务的 ACID 特性、并发事务问题及对应的隔离级别(MySQL 默认 REPEATABLE READ)。 索引基础部分,详解了 InnoDB 默认的 B+tree 索引结构(多路平衡树、叶子节点存数据、双向链表支持区间查询),区分了聚簇索引(数据与索引共存,唯一)和二级索引(数据与索引分离,多个),解释了回表查询的概念及优化方法,并分析了 B+tree 作为索引结构的优势(树高低、效率稳、支持区间查询)。 索引优化部分,列出了索引创建的六大原则
|
2月前
|
SQL 关系型数据库 MySQL
MySQL group by 底层原理详解。group by 执行 慢 原因深度分析。(图解+秒懂+史上最全)
MySQL group by 底层原理详解。group by 执行 慢 原因深度分析。(图解+秒懂+史上最全)
MySQL group by 底层原理详解。group by 执行 慢 原因深度分析。(图解+秒懂+史上最全)
|
2月前
|
存储 SQL 关系型数据库
MySQL 动态分区管理:自动化与优化实践
本文介绍了如何利用 MySQL 的存储过程与事件调度器实现动态分区管理,自动化应对数据增长,提升查询性能与数据管理效率,并详细解析了分区创建、冲突避免及实际应用中的关键注意事项。
111 0
|
4月前
|
存储 SQL 关系型数据库
京东面试:mysql深度分页 严重影响性能?根本原因是什么?如何优化?
京东面试:mysql深度分页 严重影响性能?根本原因是什么?如何优化?
京东面试:mysql深度分页 严重影响性能?根本原因是什么?如何优化?
|
6月前
|
存储 关系型数据库 MySQL
MySQL细节优化:关闭大小写敏感功能的方法。
通过这种方法,你就可以成功关闭 MySQL 的大小写敏感功能,让你的数据库操作更加便捷。
444 19
|
3月前
|
人工智能 运维 关系型数据库
数据库运维:mysql 数据库迁移方法-mysqldump
本文介绍了MySQL数据库迁移的方法与技巧,重点探讨了数据量大小对迁移方式的影响。对于10GB以下的小型数据库,推荐使用mysqldump进行逻辑导出和source导入;10GB以上可考虑mydumper与myloader工具;100GB以上则建议物理迁移。文中还提供了统计数据库及表空间大小的SQL语句,并讲解了如何使用mysqldump导出存储过程、函数和数据结构。通过结合实际应用场景选择合适的工具与方法,可实现高效的数据迁移。
628 1
|
4月前
|
负载均衡 算法 关系型数据库
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
本文聚焦 MySQL 集群架构中的负载均衡算法,阐述其重要性。详细介绍轮询、加权轮询、最少连接、加权最少连接、随机、源地址哈希等常用算法,分析各自优缺点及适用场景。并提供 Java 语言代码实现示例,助力直观理解。文章结构清晰,语言通俗易懂,对理解和应用负载均衡算法具有实用价值和参考价值。
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
|
3月前
|
SQL 关系型数据库 MySQL
Go语言数据库编程:使用 `database/sql` 与 MySQL/PostgreSQL
Go语言通过`database/sql`标准库提供统一数据库操作接口,支持MySQL、PostgreSQL等多种数据库。本文介绍了驱动安装、连接数据库、基本增删改查操作、预处理语句、事务处理及错误管理等内容,涵盖实际开发中常用的技巧与注意事项,适合快速掌握Go语言数据库编程基础。
241 62

推荐镜像

更多