MySQL - order by和 group by 优化初探

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 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


相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
99
分享
相关文章
mysql 之order by工作流程
本文深入解析了MySQL中`ORDER BY`的排序机制,通过具体示例展示了排序过程及性能优化方法。文章首先分析了基于内存和磁盘的排序方式,包括`sort_buffer_size`的影响以及临时文件的使用场景。接着介绍了`rowid`排序算法,该算法通过减少参与排序的数据量来提升性能,并对比了其与传统排序的区别。此外,还探讨了随机查询`ORDER BY RAND()`的执行流程及其优化策略。最后提到了MySQL 5.6引入的优先队列排序算法,适用于仅需部分有序结果的场景。文章结合`optimizer_trace`工具详细说明了各配置参数对排序行为的影响,为优化查询提供了实用指导。
mysql 之order by工作流程
MySQL底层概述—8.JOIN排序索引优化
本文主要介绍了MySQL中几种关键的优化技术和概念,包括Join算法原理、IN和EXISTS函数的使用场景、索引排序与额外排序(Using filesort)的区别及优化方法、以及单表和多表查询的索引优化策略。
104 22
MySQL底层概述—8.JOIN排序索引优化
【YashanDB知识库】如何将mysql含有group by的SQL转换成崖山支持的SQL
本文探讨了在YashanDB(崖山数据库)中执行某些SQL语句时出现的报错问题,对比了MySQL的成功执行结果。问题源于SQL-92标准对非聚合列的严格限制,要求这些列必须出现在GROUP BY子句中,而SQL:1999及更高版本允许非聚合列直接出现在选择列中。YashanDB和Oracle遵循SQL-92标准,因此会报错。文章提供了两种解决方法:使用聚合函数处理非聚合列,或将GROUP BY与ORDER BY拆分为两层查询。最后总结指出,SQL-92标准更为严谨合理,建议开发者遵循此规范以避免潜在问题。
MySQL底层概述—7.优化原则及慢查询
本文主要介绍了:Explain概述、Explain详解、索引优化数据准备、索引优化原则详解、慢查询设置与测试、慢查询SQL优化思路
123 15
MySQL底层概述—7.优化原则及慢查询
基于SQL Server / MySQL进行百万条数据过滤优化方案
对百万级别数据进行高效过滤查询,需要综合使用索引、查询优化、表分区、统计信息和视图等技术手段。通过合理的数据库设计和查询优化,可以显著提升查询性能,确保系统的高效稳定运行。
46 9
MySQL和SQLSugar百万条数据查询分页优化
在面对百万条数据的查询时,优化MySQL和SQLSugar的分页性能是非常重要的。通过合理使用索引、调整查询语句、使用缓存以及采用高效的分页策略,可以显著提高查询效率。本文介绍的技巧和方法,可以为开发人员在数据处理和查询优化中提供有效的指导,提升系统的性能和用户体验。掌握这些技巧后,您可以在处理海量数据时更加游刃有余。
93 9
图解MySQL【日志】——磁盘 I/O 次数过高时优化的办法
当 MySQL 磁盘 I/O 次数过高时,可通过调整参数优化。控制刷盘时机以降低频率:组提交参数 `binlog_group_commit_sync_delay` 和 `binlog_group_commit_sync_no_delay_count` 调整等待时间和事务数量;`sync_binlog=N` 设置 write 和 fsync 频率,`innodb_flush_log_at_trx_commit=2` 使提交时只写入 Redo Log 文件,由 OS 择机持久化,但两者在 OS 崩溃时有丢失数据风险。
46 3
【YashanDB 知识库】如何将 mysql 含有 group by 的 SQL 转换成崖山支持的 SQL
在崖山数据库中执行某些 SQL 语句时出现报错(YAS-04316 not a single-group group function),而这些语句在 MySQL 中能成功执行。原因是崖山遵循 SQL-92 标准,不允许选择列表中包含未在 GROUP BY 子句中指定的非聚合列,而 MySQL 默认允许这种操作。解决办法包括:使用聚合函数处理非聚合列或拆分查询为两层,先进行 GROUP BY 再排序。总结来说,SQL-92 更严格,确保数据一致性,MySQL 在 5.7 及以上版本也默认遵循此标准。
《零基础》MySQL GROUP BY 语句(十九)
GROUP BY 语句根据一个或多个列对结果集进行分组。 在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。 GROUP BY 语法
122 0
MySQL GROUP BY 语句
MySQL GROUP BY 语句 GROUP BY 语句根据一个或多个列对结果集进行分组。 在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。 GROUP BY 语法 SELECT column_name, function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; 实例演示 本章节实例使用到了以下表结构及数据,使用前我们可以先将以下数据导入数据库中。
1002 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等