EXPLAIN关键字简介
使用EXPLAIN关键字可以模拟优化器执行SQL语句,从而知道MySQL是 如何处理你的SQL语句的。分析你的查询语句或是结构的性能瓶颈
下面是使用 explain 的例子:
在 select 语句之前增加 explain 关键字,MySQL会在查询上设置一个标记,执行查询时,会返回执行计划的信息,而不是执行这条SQL(如果from 中包含子查询,仍会执行该子查询,将结果放入临时表中)
使用的表
DROP TABLE IF EXISTS `actor`;
CREATE TABLE `actor` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `actor` (`id`, `name`, `update_time`) VALUES
(1,'a','2017-12-22 15:27:18'), (2,'b','2017-12-22 15:27:18'), (3,'c','2017-12-22
15:27:18');
DROP TABLE IF EXISTS `film`;
CREATE TABLE `film` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `film` (`id`, `name`) VALUES
(3,'film0'),(1,'film1'),(2,'film2');
DROP TABLE IF EXISTS `film_actor`;
CREATE TABLE `film_actor` (
`id` int(11) NOT NULL,
`film_id` int(11) NOT NULL,
`actor_id` int(11) NOT NULL,
`remark` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_film_actor_id` (`film_id`,`actor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `film_actor` (`id`, `film_id`, `actor_id`) VALUES
(1,1,1),(2,1,2),(3,2,1);
mysql\> explain select * from actor;
在查询中的每个表会输出一行,如果有两个表通过 join连接查询,那么会输出两行。表的意义相当广泛:可以是子查询、一个 union 结果等。
explain 有两个变种:
1)explain extended:会在 explain 的基础上额外提供一些查询优化的信息。紧随其后通过 show warnings 命令可以得到优化后的查询语句,从而看出优化器优化了什么。额外还有 filtered列,是一个半分比的值,rows * filtered/100 可以估算出将要和 explain中前一个表进行连接的行数(前一个表指 explain 中的id值比当前表id值小的表)。
mysql> explain extended select * from film where id = 1;
mysql> show warnings;
2)explain partitions:相比 explain 多了个 partitions字段,如果查询是基于分区表的话,会显示查询将访问的分区。
explain 中的列
接下来我们将展示 explain 中每个列的信息。
1. id列
id列的编号是 select 的序列号,有几个 select 就有几个id,并且id的顺序是按 select出现的顺序增长的。MySQL将 select 查询分为简单查询(SIMPLE)和复杂查询(PRIMARY)。
复杂查询分为三类:简单子查询、派生表(from语句中的子查询)、union 查询。
id列越大执行优先级越高,id相同则从上往下执行,id为NULL最后执行
1)简单子查询
mysql> explain select (select 1 from actor limit 1) from film;
2)from子句中的子查询
mysql> explain select id from (select id from film) as der;
这个查询执行时有个临时表别名为der,外部 select 查询引用了这个临时表
3)union查询
mysql> explain select 1 union all select 1;
union结果总是放在一个匿名临时表中,临时表不在SQL中出现,因此它的id是NULL。
2. select_type列
select_type表示对应行是简单还是复杂的查询,如果是复杂的查询,又是上述三种复杂查询中的哪一种。
1)simple:简单查询。查询不包含子查询和union
mysql> explain select * from film where id = 2;
2)primary:复杂查询中最外层的 select
3)subquery:包含在 select 中的子查询(不在 from 子句中)
4)derived:包含在 from子句中的子查询。MySQL会将结果存放在一个临时表中,也称为派生表(derived的英文含义)
用这个例子来了解 primary、subquery 和 derived 类型
mysql> explain select (select 1 from actor where id = 1) from (select* from film where id = 1) der;
5)union:在 union 中的第二个和随后的 select
6)union result:从 union 临时表检索结果的 select
用这个例子来了解 union 和 union result 类型:
mysql> explain select 1 union all select 1;
3. table列
这一列表示 explain 的一行正在访问哪个表。
当 from 子句中有子查询时,table列是 <derivenN> 格式,表示当前查询依赖 id=N的查询,于是先执行 id=N 的查询。
当有 union 时,UNION RESULT 的 table 列的值为<union1,2>,1和2表示参与 union 的select 行id。
4. type列
这一列表示关联类型或访问类型,即MySQL决定如何查找表中的行,查找数据行记录的大概范围。
依次从最优到最差分别为:system > const > eq_ref > ref > range > index >ALL
一般来说,得保证查询达到range级别,最好达到ref
NULL:mysql能够在优化阶段分解查询语句,在执行阶段用不着再访问表或索引。例如:在索引列中选取最小值,可以单独查找索引来完成,不需要在执行时访问表
mysql> explain select min(id) from film;
const, system:mysql能对查询的某部分进行优化并将其转化成一个常量(可以看showwarnings 的结果)。用于 primary key 或 unique key的所有列与常数比较时,所以表最多有一个匹配行,读取1次,速度比较快。system是const的特例,表里只有一条元组匹配时为system
mysql> explain extended select * from (select * from film where id = 1)tmp;
mysql> show warnings;
eq_ref:primary key 或 unique key 索引的所有部分被连接使用,最多只会返回一条符合条件的记录。这可能是在 const 之外最好的联接类型了,简单的select 查询不会出现这种 type。
mysql> explain select * from film_actor left join film on film_actor.film_id =film.id;
ref:相比 eq_ref,不使用唯一索引,而是使用普通索引或者唯一性索引的部分前缀,索引要和某个值相比较,可能会找到多个符合条件的行。
1. 简单 select 查询,name是普通索引(非唯一索引) mysql> explain select *from film where name = "film1";
2.关联表查询,idx_film_actor_id是film_id和actor_id的联合索引,这里使用到了film_actor的左边前缀film_id部分。mysql> explain select film_id from film left join film_actor on film.id =film_actor.film_id;
range:范围扫描通常出现在 in(), between ,> ,<, >=等操作中。使用一个索引来检索给定范围的行。
mysql> explain select * from actor where id > 1;
index:扫描全表索引,这通常比ALL快一些。(index是从索引中读取的,而all是从硬盘中读取)
mysql> explain select * from film;
ALL:即全表扫描,意味着mysql需要从头到尾去查找所需要的行。通常情况下这需要增加索引来进行优化了
mysql> explain select * from actor;
5. possible_keys列
这一列显示查询可能使用哪些索引来查找。
explain 时可能出现 possible_keys 有列,而 key 显示 NULL的情况,这种情况是因为表中数据不多,mysql认为索引对此查询帮助不大,选择了全表查询。
如果该列是NULL,则没有相关的索引。在这种情况下,可以通过检查 where子句看是否可以创造一个适当的索引来提高查询性能,然后用 explain 查看效果。
6. key列
这一列显示mysql实际采用哪个索引来优化对该表的访问。
如果没有使用索引,则该列是NULL。如果想强制mysql使用或忽视possible_keys列中的索引,在查询中使用 forceindex、ignore index。
7. key_len列
这一列显示了mysql在索引里使用的字节数,通过这个值可以算出具体使用了索引中的哪些列。
举例来说,film_actor的联合索引 idx_film_actor_id 由 film_id 和 actor_id两个int列组成,并且每个int是4字节。通过结果中的key_len=4可推断出查询使用了第一个列:film_id列来执行索引查找。
mysql> explain select * from film_actor where film_id = 2;
key_len计算规则如下:
-
字符串
-
char(n):n字节长度
-
varchar(n):2字节存储字符串长度,如果是utf-8,则长度 3n + 2
-
-
数值类型
-
tinyint:1字节
-
smallint:2字节
-
int:4字节
-
bigint:8字节
-
-
时间类型
-
date:3字节
-
timestamp:4字节
-
datetime:8字节
-
-
如果字段允许为 NULL,需要1字节记录是否为 NULL
索引最大长度是768字节,当字符串过长时,mysql会做一个类似左前缀索引的处理,将前半部分的字符提取出来做索引。
8. ref列
这一列显示了在key列记录的索引中,表查找值所用到的列或常量,常见的有:const(常量),字段名(例:film.id)
9. rows列
这一列是mysql估计要读取并检测的行数,注意这个不是结果集里的行数。
10. Extra列
这一列展示的是额外信息。常见的重要值如下:
**Usingindex:查询的列被索引覆盖,并且where筛选条件是索引的前导列,是性能高的表现。一般是使用了覆盖索引**(索引包含了所有查询的字段)。对于innodb来说,如果是辅助索引性能会有不少提高
mysql> explain select film_id from film_actor where film_id = 1;
Using where:查询的列未被索引覆盖,where筛选条件非索引的前导列
mysql> explain select * from actor where name = 'a';
**Using where Usingindex**:查询的列被索引覆盖,并且where筛选条件是索引列之一但是不是索引的前导列,意味着无法直接通过索引查找来查询到符合条件的数据
mysql> explain select film_id from film_actor where actor_id = 1;
NULL:查询的列未被索引覆盖,并且where筛选条件是索引的前导列,意味着用到了索引,但是部分字段未被索引覆盖,必须通过“回表”来实现,不是纯粹地用到了索引,也不是完全没用到索引
mysql>explain select * from film_actor where film_id = 1;
Using index condition:与Usingwhere类似,查询的列不完全被索引覆盖,where条件中是一个前导列的范围;
mysql> explain select * from film_actor where film_id > 1;
Usingtemporary:mysql需要创建一张临时表来处理查询。出现这种情况一般是要进行优化的,首先是想到用索引来优化。
1. actor.name没有索引,此时创建了张临时表来distinct mysql> explain selectdistinct name from actor;
2. film.name建立了idx_name索引,此时查询时extra是using index,没有用临时表mysql> explain select distinct name from film;
Using filesort:mysql会对结果使用一个外部索引排序,而不是按索引次序从表里读取行。此时mysql会根据联接类型浏览所有符合条件的记录,并保存排序关键字和行指针,然后排序关键字并按顺序检索行信息。这种情况下一般也是要考虑使用索引来优化的。
1.actor.name未创建索引,会浏览actor整个表,保存排序关键字name和对应的id,然后排序name并检索行记录mysql> explain select * from actor order by name;
2. film.name建立了idx_name索引,此时查询时extra是using indexmysql> explainselect * from film order by name;
索引最佳实践
使用的表
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=4 DEFAULT CHARSET=utf8 COMMENT='员工记录表';
INSERT INTO employees(name,age,position,hire_time)VALUES('LiLei',22,'manager',NOW());
INSERT INTO employees(name,age,position,hire_time) VALUES('HanMeimei',23,'dev',NOW());
INSERT INTO employees(name,age,position,hire_time)VALUES('Lucy',23,'dev',NOW());
1. 全值匹配
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei';
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22;
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position='manager';
2.最佳左前缀法则
如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。
EXPLAIN SELECT * FROM employees WHERE age = 22 AND position ='manager';
EXPLAIN SELECT * FROM employees WHERE position = 'manager';
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';
3.不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';
EXPLAIN SELECT * FROM employees WHERE left(name,3) = 'LiLei';
4.存储引擎不能使用索引中范围条件右边的列
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position='manager';
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age > 22 AND position='manager';
5.尽量使用覆盖索引(只访问索引的查询(索引列包含查询列)),减少select*语句
EXPLAIN SELECT name,age FROM employees WHERE name= 'LiLei' AND age = 23 ANDposition ='manager';
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 23 AND position='manager';
6.mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描
EXPLAIN SELECT * FROM employees WHERE name != 'LiLei'
7.is null,is not null 也无法使用索引
EXPLAIN SELECT * FROM employees WHERE name is null
8.like以通配符开头('$abc...')mysql索引失效会变成全表扫描操作
EXPLAIN SELECT * FROM employees WHERE name like '%Lei'
EXPLAIN SELECT * FROM employees WHERE name like 'Lei%'
问题:解决like'%字符串%'索引不被使用的方法?
a)使用覆盖索引,查询字段必须是建立覆盖索引字段
EXPLAIN SELECT name,age,position FROM employees WHERE name like '%Lei%';
b)当覆盖索引指向的字段是varchar(380)及380以上的字段时,覆盖索引会失效!
9.字符串不加单引号索引失效
EXPLAIN SELECT * FROM employees WHERE name = '1000';
EXPLAIN SELECT * FROM employees WHERE name = 1000;
10.少用or,用它连接时很多情况下索引会失效
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' or name = 'HanMeimei';
11.无法避免对索引列使用函数,怎么使用索引
有时候我们无法避免对索引列使用函数,但这样做会导致全表索引,是否有更好的方式呢。
比如我现在就是想记录 1990年到1993所有年份 7月份的员工入职人数
SELECT COUNT(*) from employees WHERE month(hire_date)=7;
由于索引列是函数的参数,所以显然无法用到索引,我们可以将它改造成基本字段区间的查找如下
EXPLAIN SELECT COUNT(1) from employees WHERE
(hire_date>='1990-7-1' AND hire_date<'1990-8-1')
OR
(hire_date>='1991-7-1' AND hire_date<'1991-8-1')
OR
(hire_date>='1992-7-1' AND hire_date<'1992-8-1')
;
总结:
索引使用注意事项:
like KK%相当于=常量,%KK和%KK% 相当于范围
性能排序:
性能按照type排序:
system > const > eq_ref > ref > ref_or_null > index_merge > unique_subquery > index_subquery > range >
index > ALL
性能按照extra排序:
- Using index:用了覆盖索引
- Using index condition:用了条件索引(索引下推)
- Using where:从索引查出来数据后继续用where条件过滤
- Using join buffer (Block Nested Loop): join的时候利用了join buffer(优化策略:去除外连接、增大join buffer大小)
- Using filesort:用了文件排序,排序的时候没有用到索引
- Using temporary:用了临时表(优化策略:增加条件以减少结果集、增加索引,思路就是要么减少待排序的数量,要么就提前排好序)
- Start temporary, End temporary:子查询的时候,可以优化成半连接,但是使用的是通过临时表来去重
- FirstMatch(tbl_name):子查询的时候,可以优化成半连接,但是使用的是直接进行数据比较来去重
常用优化手段
1.SQL语句中IN包含的值不应过多,不能超过200个, 200个以内查询优化器计算成本时比较精准,超过200
个是估算的成本,另外建议能用between就不要用in,这样就可以使用range索引了。
2. SELECT语句务必指明字段名称: SELECT * 增加很多不必要的消耗( cpu、 io、内存、网络带宽);增加
了使用覆盖索引的可能性;当表结构发生改变时,前断也需要更新。所以要求直接在select后面接上字段
名。
3. 当只需要一条数据的时候,使用limit 1
4. 排序时注意是否能用到索引
5. 使用or时如果没有用到索引,可以改为union all 或者union
6. 如果in不能用到索引,可以改成exists看是否能用到索引
7. 使用合理的分页方式以提高分页的效率
8. 不建议使用%前缀模糊查询
9. 避免在where子句中对字段进行表达式操作
10. 避免隐式类型转换
11. 对于联合索引来说,要遵守最左前缀法则
12. 必要时可以使用force index来强制查询走某个索引
13. 对于联合索引来说,如果存在范围查询,比如between,>,<等条件时,会造成后面的索引字段失效。
14. 尽量使用inner join,避免left join,让查询优化器来自动选择小表作为驱动表
15. 必要时刻可以使用straight_join来指定驱动表,前提条件是本身是inner join
Using filesort文件排序原理详解
filesort文件排序方式
- 单路排序:是一次性取出满足条件行的所有字段,然后在sort buffer中进行排序;用trace工具可以看到sort_mode信息里显示< sort_key, additional_fields >或者< sort_key,packed_additional_fields>
- 双路排序(又叫回表排序模式):是首先根据相应的条件取出相应的排序字段和可以直接定位行数据的行 ID,然后在 sort buffer 中进行排序,排序完后需要再次取回其它需要的字段;用trace工具可以看到sort_mode信息里显示< sort_key, rowid >
MySQL 通过比较系统变量 max_length_for_sort_data(默认1024字节) 的大小和需要查询的字段总大小来
判断使用哪种排序模式。
- 如果 max_length_for_sort_data 比查询字段的总长度大,那么使用 单路排序模式;
- 如果 max_length_for_sort_data 比查询字段的总长度小,那么使用 双路排序模式。
示例验证下各种排序方式:
查看下这条sql对应trace结果如下(只展示排序部分):
select * from employees where name = 'zhuge' order by position;
SELECT * FROM information_schema.OPTIMIZER_TRACE;{
"steps": [{
"join_preparation": {
"select#": 1,
"steps": [{
"expanded_query": "/* select#1 */ select `employees`.`id` AS `id`,`employees`.`name` AS `name`,`employees`.`age` AS `age`,`employees`.`position` AS `position`,`employees`.`hire_time` AS `hire_time` from `employees` where (`employees`.`name` = 'zhuge') order by `employees`.`position`"
}]
}
},
{
"join_optimization": {
"select#": 1,
"steps": [{
"condition_processing": {
"condition": "WHERE",
"original_condition": "(`employees`.`name` = 'zhuge')",
"steps": [{
"transformation": "equality_propagation",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
},
{
"transformation": "constant_propagation",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
},
{
"transformation": "trivial_condition_removal",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
}
] /* steps */
} /* condition_processing */
},
{
"substitute_generated_columns": {} /* substitute_generated_columns */
},
{
"table_dependencies": [{
"table": "`employees`",
"row_may_be_null": false,
"map_bit": 0,
"depends_on_map_bits": [] /* depends_on_map_bits */
}] /* table_dependencies */
},
{
"ref_optimizer_key_uses": [{
"table": "`employees`",
"field": "name",
"equals": "'zhuge'",
"null_rejecting": false
}] /* ref_optimizer_key_uses */
},
{
"rows_estimation": [{
"table": "`employees`",
"range_analysis": {
"table_scan": {
"rows": 100260,
"cost": 20407
} /* table_scan */ ,
"potential_range_indexes": [{
"index": "PRIMARY",
"usable": false,
"cause": "not_applicable"
},
{
"index": "idx_name_age_position",
"usable": true,
"key_parts": [
"name",
"age",
"position",
"id"
] /* key_parts */
}
] /* potential_range_indexes */ ,
"setup_range_conditions": [] /* setup_range_conditions */ ,
"group_index_range": {
"chosen": false,
"cause": "not_group_by_or_distinct"
} /* group_index_range */ ,
"analyzing_range_alternatives": {
"range_scan_alternatives": [{
"index": "idx_name_age_position",
"ranges": [
"zhuge <= name <= zhuge"
] /* ranges */ ,
"index_dives_for_eq_ranges": true,
"rowid_ordered": false,
"using_mrr": false,
"index_only": false,
"rows": 18818,
"cost": 22583,
"chosen": false,
"cause": "cost"
}] /* range_scan_alternatives */ ,
"analyzing_roworder_intersect": {
"usable": false,
"cause": "too_few_roworder_scans"
} /* analyzing_roworder_intersect */
} /* analyzing_range_alternatives */
} /* range_analysis */
}] /* rows_estimation */
},
{
"considered_execution_plans": [{
"plan_prefix": [] /* plan_prefix */ ,
"table": "`employees`",
"best_access_path": {
"considered_access_paths": [{
"access_type": "ref",
"index": "idx_name_age_position",
"rows": 18818,
"cost": 4822.6,
"chosen": true
},
{
"rows_to_scan": 100260,
"access_type": "scan",
"resulting_rows": 100260,
"cost": 20405,
"chosen": false
}
] /* considered_access_paths */
} /* best_access_path */ ,
"condition_filtering_pct": 100,
"rows_for_plan": 18818,
"cost_for_plan": 4822.6,
"chosen": true
}] /* considered_execution_plans */
},
{
"attaching_conditions_to_tables": {
"original_condition": "(`employees`.`name` = 'zhuge')",
"attached_conditions_computation": [] /* attached_conditions_computation */ ,
"attached_conditions_summary": [{
"table": "`employees`",
"attached": null
}] /* attached_conditions_summary */
} /* attaching_conditions_to_tables */
},
{
"clause_processing": {
"clause": "ORDER BY",
"original_clause": "`employees`.`position`",
"items": [{
"item": "`employees`.`position`"
}] /* items */ ,
"resulting_clause_is_simple": true,
"resulting_clause": "`employees`.`position`"
} /* clause_processing */
},
{
"added_back_ref_condition": "((`employees`.`name` <=> 'zhuge'))"
},
{
"reconsidering_access_paths_for_index_ordering": {
"clause": "ORDER BY",
"steps": [] /* steps */ ,
"index_order_summary": {
"table": "`employees`",
"index_provides_order": false,
"order_direction": "undefined",
"index": "idx_name_age_position",
"plan_changed": false
} /* index_order_summary */
} /* reconsidering_access_paths_for_index_ordering */
},
{
"refine_plan": [{
"table": "`employees`",
"pushed_index_condition": "(`employees`.`name` <=> 'zhuge')",
"table_condition_attached": null
}] /* refine_plan */
}
] /* steps */
} /* join_optimization */
},
{
"join_execution": {
"select#": 1,
"steps": [{
"filesort_information": [{
"direction": "asc",
"table": "`employees`",
"field": "position"
}] /* filesort_information */ ,
"filesort_priority_queue_optimization": {
"usable": false,
"cause": "not applicable (no LIMIT)"
} /* filesort_priority_queue_optimization */ ,
"filesort_execution": [] /* filesort_execution */ ,
"filesort_summary": { ‐‐文件排序信息
"rows": 9999, ‐‐预计扫描行数
"examined_rows": 9999, ‐‐参数排序的行
"number_of_tmp_files": 3, ‐‐使用临时文件的个数,这个值如果为0代表全部使用的sort_buffer内存排序,否则使用的磁盘文件排序
"sort_buffer_size": 262056, ‐‐排序缓存的大小
"sort_mode": "<sort_key, packed_additional_fields>" ‐‐排序方式,这里用的单路排序
} /* filesort_summary */
}] /* steps */
} /* join_execution */
}
] /* steps */
}
设置
set max_length_for_sort_data = 10; ‐‐employees表所有字段长度总和肯定大于10字节
select * from employees where name = 'zhuge' order by position;
select * from information_schema.OPTIMIZER_TRACE;
trace排序部分结果:
{
"steps": [{
"join_preparation": {
"select#": 1,
"steps": [{
"expanded_query": "/* select#1 */ select `employees`.`id` AS `id`,`employees`.`name` AS `name`,`employees`.`age` AS `age`,`employees`.`position` AS `position`,`employees`.`hire_time` AS `hire_time` from `employees` where (`employees`.`name` = 'zhuge') order by `employees`.`position`"
}]
}
},
{
"join_optimization": {
"select#": 1,
"steps": [{
"condition_processing": {
"condition": "WHERE",
"original_condition": "(`employees`.`name` = 'zhuge')",
"steps": [{
"transformation": "equality_propagation",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
},
{
"transformation": "constant_propagation",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
},
{
"transformation": "trivial_condition_removal",
"resulting_condition": "(`employees`.`name` = 'zhuge')"
}
] /* steps */
} /* condition_processing */
},
{
"substitute_generated_columns": {} /* substitute_generated_columns */
},
{
"table_dependencies": [{
"table": "`employees`",
"row_may_be_null": false,
"map_bit": 0,
"depends_on_map_bits": [] /* depends_on_map_bits */
}] /* table_dependencies */
},
{
"ref_optimizer_key_uses": [{
"table": "`employees`",
"field": "name",
"equals": "'zhuge'",
"null_rejecting": false
}] /* ref_optimizer_key_uses */
},
{
"rows_estimation": [{
"table": "`employees`",
"range_analysis": {
"table_scan": {
"rows": 100260,
"cost": 20407
} /* table_scan */ ,
"potential_range_indexes": [{
"index": "PRIMARY",
"usable": false,
"cause": "not_applicable"
},
{
"index": "idx_name_age_position",
"usable": true,
"key_parts": [
"name",
"age",
"position",
"id"
] /* key_parts */
}
] /* potential_range_indexes */ ,
"setup_range_conditions": [] /* setup_range_conditions */ ,
"group_index_range": {
"chosen": false,
"cause": "not_group_by_or_distinct"
} /* group_index_range */ ,
"analyzing_range_alternatives": {
"range_scan_alternatives": [{
"index": "idx_name_age_position",
"ranges": [
"zhuge <= name <= zhuge"
] /* ranges */ ,
"index_dives_for_eq_ranges": true,
"rowid_ordered": false,
"using_mrr": false,
"index_only": false,
"rows": 18818,
"cost": 22583,
"chosen": false,
"cause": "cost"
}] /* range_scan_alternatives */ ,
"analyzing_roworder_intersect": {
"usable": false,
"cause": "too_few_roworder_scans"
} /* analyzing_roworder_intersect */
} /* analyzing_range_alternatives */
} /* range_analysis */
}] /* rows_estimation */
},
{
"considered_execution_plans": [{
"plan_prefix": [] /* plan_prefix */ ,
"table": "`employees`",
"best_access_path": {
"considered_access_paths": [{
"access_type": "ref",
"index": "idx_name_age_position",
"rows": 18818,
"cost": 4822.6,
"chosen": true
},
{
"rows_to_scan": 100260,
"access_type": "scan",
"resulting_rows": 100260,
"cost": 20405,
"chosen": false
}
] /* considered_access_paths */
} /* best_access_path */ ,
"condition_filtering_pct": 100,
"rows_for_plan": 18818,
"cost_for_plan": 4822.6,
"chosen": true
}] /* considered_execution_plans */
},
{
"attaching_conditions_to_tables": {
"original_condition": "(`employees`.`name` = 'zhuge')",
"attached_conditions_computation": [] /* attached_conditions_computation */ ,
"attached_conditions_summary": [{
"table": "`employees`",
"attached": null
}] /* attached_conditions_summary */
} /* attaching_conditions_to_tables */
},
{
"clause_processing": {
"clause": "ORDER BY",
"original_clause": "`employees`.`position`",
"items": [{
"item": "`employees`.`position`"
}] /* items */ ,
"resulting_clause_is_simple": true,
"resulting_clause": "`employees`.`position`"
} /* clause_processing */
},
{
"added_back_ref_condition": "((`employees`.`name` <=> 'zhuge'))"
},
{
"reconsidering_access_paths_for_index_ordering": {
"clause": "ORDER BY",
"steps": [] /* steps */ ,
"index_order_summary": {
"table": "`employees`",
"index_provides_order": false,
"order_direction": "undefined",
"index": "idx_name_age_position",
"plan_changed": false
} /* index_order_summary */
} /* reconsidering_access_paths_for_index_ordering */
},
{
"refine_plan": [{
"table": "`employees`",
"pushed_index_condition": "(`employees`.`name` <=> 'zhuge')",
"table_condition_attached": null
}] /* refine_plan */
}
] /* steps */
} /* join_optimization */
},
{
"join_execution": {
"select#": 1,
"steps": [{
"filesort_information": [{
"direction": "asc",
"table": "`employees`",
"field": "position"
}] /* filesort_information */ ,
"filesort_priority_queue_optimization": {
"usable": false,
"cause": "not applicable (no LIMIT)"
} /* filesort_priority_queue_optimization */ ,
"filesort_execution": [] /* filesort_execution */ ,
"filesort_summary": {
"rows": 9999,
"examined_rows": 9999,
"number_of_tmp_files": 2,
"sort_buffer_size": 262136,
"sort_mode": "<sort_key, rowid>" ‐‐排序方式,这里用的双路排序
} /* filesort_summary */
}] /* steps */
} /* join_execution */
}
] /* steps */
}
我们先看单路排序的详细过程:
1. 从索引name找到第一个满足 name = ‘zhuge’ 条件的主键 id
2. 根据主键 id 取出整行,取出所有字段的值,存入 sort_buffer 中
3. 从索引name找到下一个满足 name = ‘zhuge’ 条件的主键 id
4. 重复步骤 2、3 直到不满足 name = ‘zhuge’
5. 对 sort_buffer 中的数据按照字段 position 进行排序
6. 返回结果给客户端
我们再看下双路排序的详细过程:
1. 从索引 name 找到第一个满足 name = ‘zhuge’ 的主键id
2. 根据主键 id 取出整行,把排序字段 position 和主键 id 这两个字段放到 sort buffer 中
3. 从索引 name 取下一个满足 name = ‘zhuge’ 记录的主键 id
4. 重复 3、4 直到不满足 name = ‘zhuge
5. 对 sort_buffer 中的字段 position 和主键 id 按照字段 position 进行排序
6. 遍历排序好的 id 和字段 position,按照 id 的值回到原表中取出 所有字段的值返回给客户端
其实对比两个排序模式,单路排序会把所有需要查询的字段都放到 sort buffer 中,而双路排序只会把主键和需要排序的字段放到 sort buffer 中进行排序,然后再通过主键回到原表查询需要的字段。如果 MySQL 排序内存配置的比较小并且没有条件继续增加了,可以适当把 max_length_for_sort_data 配置小点,让优化器选择使用双路排序算法,可以在sort_buffer 中一次排序更多的行,只是需要再根据主键回到原表取数据。
如果 MySQL 排序内存有条件可以配置比较大,可以适当增大 max_length_for_sort_data 的值,让优化器优先选择全字段排序(单路排序),把需要的字段放到 sort_buffer 中,这样排序后就会直接从内存里返回查询结果了。
所以,MySQL通过 max_length_for_sort_data 这个参数来控制排序,在不同场景使用不同的排序模式,从而提升排序效率。
注意,如果全部使用sort_buffer内存排序一般情况下效率会高于磁盘文件排序,但不能因为这个就随便增大sort_buffer(默认1M),mysql很多参数设置都是做过优化的,不要轻易调