站长资讯网
最全最丰富的资讯网站

实践(2)–MySQL性能优化

实践(2)--MySQL性能优化

相关学习推荐:mysql教程

前言

  • MySQL索引底层数据结构与算法
  • MySQL性能优化原理-前篇
  • 实践(1)–MySQL性能优化

上一篇 《实践(1)–MySQL性能优化》我们讲了数据库表设计的一些原则,Explain工具的介绍、SQL语句优化索引的最佳实践,本篇继续来聊聊 MySQL 如何选择合适的索引。

MySQL Trace 工具

MySQL 最终是否选择走索引或者一张表涉及多个索引,最终是如何选择索引,可以使用 trace 工具来一查究竟,开启 trace工具会影响 MySQL 性能,所以只能临时分析 SQL 使用,用完之后立即关闭。

案例分析

讲 trace 工具之前我们先来看一个案例:

# 示例表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('ZhangSan',23,'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());复制代码

MySQL 如何选择合适的索引

EXPLAIN select * from employees where name > 'a';复制代码
实践(2)--MySQL性能优化

如果用name索引需要遍历name字段联合索引树,然后还需要根据遍历出来的主键值去主键索引树里再去查出最终数据,成本比全表扫描还高,可以用覆盖索引优化,这样只需要遍历name字段的联合索引树就能拿到所有结果,如下:

EXPLAIN select name,age,position from employees where name > 'a' ;复制代码
实践(2)--MySQL性能优化
EXPLAIN select * from employees where name > 'zzz' ;复制代码

对于上面这两种 name>'a'name>'zzz' 的执行结果,mysql最终是否选择走索引或者一张表涉及多个索引,mysql最终如何选择索引,我们可以用trace工具来一查究竟,开启trace工具会影响mysql性能,所以只能临时分析sql使用,用完之后立即关闭。

trace工具用法

开启/关闭Trace

#开启traceset session optimizer_trace="enabled=on",end_markers_in_json=on; #关闭traceset session optimizer_trace="enabled=off";复制代码

案例1

执行这两句sql

select * from employees where name >'a' order by position;sELECT * FROM information_schema.OPTIMIZER_TRACE;  复制代码

提出来trace值,详见注释

{  "steps": [     {      "join_preparation": { --第一阶段:SQL准备阶段        "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` > 'a') order by `employees`.`position`"           }         ] /* steps */       } /* join_preparation */     },     {      "join_optimization": { --第二阶段:SQL优化阶段        "select#": 1,        "steps": [           {            "condition_processing": { --条件处理              "condition": "WHERE",              "original_condition": "(`employees`.`name` > 'a')",              "steps": [                 {                  "transformation": "equality_propagation",                  "resulting_condition": "(`employees`.`name` > 'a')"                 },                 {                  "transformation": "constant_propagation",                  "resulting_condition": "(`employees`.`name` > 'a')"                 },                 {                  "transformation": "trivial_condition_removal",                  "resulting_condition": "(`employees`.`name` > 'a')"                 }               ] /* 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": [             ] /* ref_optimizer_key_uses */           },           {            "rows_estimation": [ --预估表的访问成本               {                "table": "`employees`",                "range_analysis": {                  "table_scan": { --全表扫描                    "rows": 3,  --扫描行数                    "cost": 3.7 --查询成本                   } /* 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 */                     },                     {                      "index": "idx_age",                      "usable": false,                      "cause": "not_applicable"                     }                   ] /* 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": [                          "a < name"    --索引使用范围                         ] /* ranges */,                        "index_pes_for_eq_ranges": true,                        "rowid_ordered": false, --使用该索引获取的记录是否按照主键排序                        "using_mrr": false,                        "index_only": false,    --是否使用覆盖索引                        "rows": 3,  --索引扫描行数                        "cost": 4.61, --索引使用成本                        "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": [ --最终选择的访问路径                     {                      "rows_to_scan": 3,                      "access_type": "scan",    --访问类型:为sacn,全表扫描                      "resulting_rows": 3,                      "cost": 1.6,                      "chosen": true,   --确定选择                      "use_tmp_table": true                     }                   ] /* considered_access_paths */                 } /* best_access_path */,                "condition_filtering_pct": 100,                "rows_for_plan": 3,                "cost_for_plan": 1.6,                "sort_cost": 3,                "new_cost_for_plan": 4.6,                "chosen": true               }             ] /* considered_execution_plans */           },           {            "attaching_conditions_to_tables": {              "original_condition": "(`employees`.`name` > 'a')",              "attached_conditions_computation": [               ] /* attached_conditions_computation */,              "attached_conditions_summary": [                 {                  "table": "`employees`",                  "attached": "(`employees`.`name` > 'a')"                 }               ] /* 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 */           },           {            "reconsidering_access_paths_for_index_ordering": {              "clause": "ORDER BY",              "index_order_summary": {                "table": "`employees`",                "index_provides_order": false,                "order_direction": "undefined",                "index": "unknown",                "plan_changed": false               } /* index_order_summary */             } /* reconsidering_access_paths_for_index_ordering */           },           {            "refine_plan": [               {                "table": "`employees`"               }             ] /* refine_plan */           }         ] /* steps */       } /* join_optimization */     },     {      "join_execution": {   --第三阶段:SQL执行阶段                                                            "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": 3,              "examined_rows": 3,              "number_of_tmp_files": 0,              "sort_buffer_size": 200704,              "sort_mode": "<sort_key, packed_additional_fields>"             } /* filesort_summary */           }         ] /* steps */       } /* join_execution */     }   ] /* steps */ }复制代码

结论:全表扫描的成本低于索引扫描,所以MySQL最终选择全表扫描。

案例2

select * from employees where name > 'zzz' order by position;SELECT * FROM information_schema.OPTIMIZER_TRACE;  复制代码

结论:查看trace字段可知索引扫描的成本低于全表扫描,所以MySQL最终选择索引扫描。

常见SQL深入优化

Order byGroup by 优化

案例1

EXPLAIN select * from employees where name = 'ZhangSan' and position = 'dev' order by age复制代码
实践(2)--MySQL性能优化

分析:

利用最左前缀法则:中间字段不能断,因此查询用到了 name索引 ,从 key_len = 74 也能看出,age 索引列用在排序过程过程中,因为 Extra 字段里没有 using filesort

案例2

EXPLAIN select * from employees where name = 'ZhangSan' order by position复制代码
实践(2)--MySQL性能优化

分析:

从 explain 的执行结果来看:key_len = 74,查询使用了 name 索引,由于用了 position 进行排序,跳过了 age,出现了 Using filesort

案例3

EXPLAIN select * from employees where name = 'ZhangSan' order by age,position复制代码
实践(2)--MySQL性能优化

分析:

查询只用到索引name,age 和 position 用于排序,无Using filesort

案例4

EXPLAIN select * from employees where name = 'ZhangSan' order by position,age复制代码
实践(2)--MySQL性能优化

分析:

和案例3中explain的执行结果一样,但是出现了Using filesort ,因为索引的创建顺序为 name,age,position , 但是排序的时候 age 和 position 颠倒位置了。

案例5

EXPLAIN select * from employees where name = 'ZhangSan' and age = 18 order by position,age复制代码
实践(2)--MySQL性能优化

分析:

与案例4对比,在Extra中并未出现** Using filesort **,因为 age 为常量,在排序中被优化,所以索引未颠倒,不会出现 Using filesort

案例6

EXPLAIN select * from employees where name = 'ZhangSan' order by age asc, position desc;复制代码
实践(2)--MySQL性能优化

分析:

虽然排序的字段列与索引顺序一样,且 order by 默认升序,这里 position desc 变成列降序,导致与索引的排序方式不同,从而产生 Using filesort 。MySQL8 以上版本有降序索引可以支持该种查询方式。

案例7

EXPLAIN select * from employees where name in ('ZhangSan', 'hjh') order by age, position;复制代码

分析:

对于排序来说,多个相等条件也是范围查询。

案例8

EXPLAIN select * from employees where name > 'a' order by name;复制代码
实践(2)--MySQL性能优化

可以用覆盖索引优化

EXPLAIN select name,age,position from employees where name > 'a' order by name;复制代码
实践(2)--MySQL性能优化

优化总结

  1. MySQL支持两种方式的排序 filesortindex。Using index 是指MySQL 扫描索引本身完成排序。index 效率高,filesort 效率低。
  2. order by 满足两种情况会使用 Using index.
    • order by 语句使用索引最左前例
    • 使用 where 子句与 order by 子句条件列组合满足索引最左前例
  3. 尽量在索引列上完成排序,遵循索引建立索引创建的顺序)时的最左前缀法则。
  4. 如果 order by 的条件不在索引列上,就会产生 Using filesort。
  5. 能用覆盖索引尽量用覆盖索引。
  6. group by 和 order by 很类似,其实质是先排序后分组,遵循索引创建顺序的最左前缀法则。对于 group by 的优化如果不需要排序的可以加上 order by null 禁止排序。注意:where 高于 having,能写在 where 中的限定条件就不要去 having 限定了。

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 比查询字段的总长度小,那么使用双路排序模式。

验证各种排序方式

EXPLAIN select * from employees where name = 'ZhangSan' order by position;复制代码
实践(2)--MySQL性能优化

查看下这条sql对应trace结果如下(只展示排序部分):

set session optimizer_trace="enabled=on",end_markers_in_json=on; #开启traceselect * from employees where name = 'ZhangSan' order by position;select * from information_schema.OPTIMIZER_TRACE;复制代码
      "join_execution": { --SQL执行阶段         "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": 1, --预计扫描行数               "examined_rows": 1, --参数排序的行               "number_of_tmp_files": 0, --使用临时文件的个数,这个只如果为0代表全部使用的sort_buffer内存排序,否则使用的磁盘文件排序               "sort_buffer_size": 200704, --排序缓存的大小               "sort_mode": "<sort_key, packed_additional_fields>" --排序方式,这里用的单路排序             } /* filesort_summary */           }         ] /* steps */       } /* join_execution */复制代码

修改系统变量 max_length_for_sort_data (默认1024字节) ,employees 表所有字段长度总和肯定大于10字节

set max_length_for_sort_data = 10;  select * from employees where name = 'ZhangSan' order by position;select * from information_schema.OPTIMIZER_TRACE;复制代码

trace排序部分结果:

      "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": 1,               "examined_rows": 1,               "number_of_tmp_files": 0,               "sort_buffer_size": 53248,               "sort_mode": "<sort_key, rowid>" --排序方式,这里用饿的双路排序             } /* filesort_summary */           }         ] /* steps */       } /* join_execution */    复制代码

单路排序的详细过程:

  1. 从索引 name 找到第一个满足 name='ZhangSan' 条件的主键 id;
  2. 根据主键id取出整行,取出所有字段的值,存入sort_buffer中
  3. 从索引name找到下一个满足 name='ZhangSan' 条件的主键 id;
  4. 重复步骤2、3直到不满足 name='ZhangSan';
  5. 对 sort_buffer 中的数据按照字段 position 进行排序;
  6. 返回结果给客户端

双路排序的详细过程:

  1. 从索引 name 找到第一个满足 name='ZhangSan' 的主键id;
  2. 根据主键id取出整行,把排序字段 position 和 主键id 这两个字段放到 sort_buffer 中
  3. 从索引 name 取下一个满足 name='ZhangSan' 记录的主键id;
  4. 重复步骤3、4直到不满足 name='ZhangSan';
  5. 对 sort_buffer 中的字段 position 和 主键id按照 position 进行排序;
  6. 遍历排序好的 id 和 字段 position,按照 id 的值回到原表中取出所有的字段的值返回给客户端。

对比两个排序模式,单路排序会把所有需要查询的字段都放到 sort_buffer 中,而双路排序只会把主键和需要排序的字段放到 sort_buffer 中进行排序,然后再通过主键回到原表查询需要的字段。

如果MySQL排序内存配置的比较小并且没有条件继续增加了,可以适当把 max_length_for_sort_data 配置小点,让优化器选择使用双路排序算法,可以在 sort_buffer 中一次排序

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号