导入示例数据

通过命令导入数据库文件

  1. mysql -uroot -pWolfCode_2021 -h 192.168.26.139 -t < employees.sql

其中数据模型为:
MySQL性能分析工具 - 图1

  • employees: 员工信息表, 主键是 员工编号 emp_no
  • departments: 部门表, 主键是 部门编号 dept_no
  • titles: 员工职称表, 其中员工编号emp_no, 职称名称title, 开始日期from_date是一起作为联合主键
  • salaries: 薪资表, 主键是 员工编号 emp_no,开始日期from_date作为联合主键
  • dept_manager: 部门管理者 其中员工编号emp_no, 部门编号dept_no 作为联合主键
  • dept_emp: 员工和部门关联表,其中员工编号emp_no, 部门编号dept_no 作为联合主键 其中一个员工有多个部门, 一个部门有多个员工ySQL数据库系统架构

很多时候我们需要分析我们的一个查询的SQL语句执行的性能,有没有走索引, 是否有一些性能比较差的操作, 比如使用了临时表空间, 使用了文件排序, SQL语句没有按照我们的要求进行执行.这个时候我们可以使用Explain工具进行SQL语句的分析, 在我们查询的SQL语句前面 添加一个关键字 explain .
explain 分析的是SQL语句的执行计划, 并不会根据sql语句去查询数据, 如果在SQL语句中有子查询在from 子句, 则会执行

Explain的基本使用

  1. -- 查看SQL语句的执行计划
  2. explain select * from employees;

image.png
对于执行计划中的具体的列信息, 给大家简单介绍一下

  1. id

    id列的编号是select语句的编号, 每个select语句都会有一个id编号

  • id列的值越大, 对应的SQL语句越先执行
  • 如果id值是一样的, 则从上往下依次执行
  • 如果id值为null, 则最后在执行
    EXPLAIN 
    SELECT * FROM employees WHERE emp_no='10001' 
    UNION 
    SELECT * FROM employees WHERE emp_no='10002';
    
    image.png
  1. select_type

select_type 表示对应行是简单还是复杂的查询

  • simple: 简单查询, 查询语句不包括子查询和union

    explain SELECT * FROM employees WHERE emp_no='10002';
    
  • primary:复杂查询中最外层的 select

  • subquery:包含在 select 中的子查询(不在 from 子句中)
  • derived:包含在 from 子句中的子查询。MySQL会将结果存放在一个临时表中,也称为派生表(derived的英文含义)

默认情况MySQL会帮我们对一些查询进行优化, 我们先关闭对应的一个优化项

set session optimizer_switch='derived_merge=off';
explain 
select (select avg(emp_no) from employees where emp_no<10005),avg(t1.emp_no)   
from  (select * from employees) t1;

image.png
还原默认配置

set session optimizer_switch='derived_merge=on';
  • union:在 union 中的第二个和随后的 select
    EXPLAIN 
    SELECT * FROM  employees where emp_no = '10001' 
    UNION
    SELECT * FROM  employees where emp_no = '10002'
    
    image.png
  1. table

这个列主要显示的是我们查询的数据表是哪个, 但是有时候我们会看到有一些特殊情况

  • 表示的是id为2和id为3的查询结果集的联合
  • 代表的是基于id为2的一个派生表
  1. type

联接类型。下面给出各种联接类型,按照从最佳类型到最坏类型进行排序:
system>const>eq_ref>ref>range>index>ALL

  • system: 表仅有一行(=系统表)。这是const联接类型的一个特例。
  • const: 表最多有一个匹配行,它将在查询开始时被读取。因为仅有一行,在这行的列值可被优化器剩余部分认为是常数。const表很快,因为它们只读取一次!
  • eq_ref:简单来说,就是多表连接中使用primary key或者 unique key作为关联条件
  • ref:对于每个来自于前面的表的行组合,所有有匹配索引值的行将从这张表中读取。
  • range:只检索给定范围的行,使用一个索引来选择行。
  • index:该联接类型与ALL相同,除了只有索引树被扫描。这通常比ALL快,因为索引文件通常比数据文件小。
  • ALL:对于每个来自于先前的表的行组合,进行完整的表扫描。
  • NULL:MySQL能够在优化阶段分解查询语句,在执行阶段用不着再访问表或索引。例如:在索引列中选取最小值,可以单独查找索引来完成,不需要在执行时访问表
    -- type 为null 
    explain select max(emp_no) from employees;
    -- type 为system  查询的表中本身只有一条记录
    explain select * from (select 1 from dual) tmp;
    -- type 为const 通过唯一索引或者主键索引进行 使用常量查询
    explain select * from employees where emp_no=10001;
    -- type 为 eq_ref  使用唯一索引或者主键索引进行关联
    explain select * from salaries s left join employees emp   on emp.emp_no = s.emp_no
    -- type 为 ref 使用普通索引的连接
    -- 给员工表hire_date添加普通索引
    alter table employees add index idx_hire_date(hire_date);
    explain select * from employees emp join titles t on emp.hire_date = t.from_date
    -- type 为 range 使用范围查询
    explain select * from employees where emp_no < 10086
    -- type 为 index 扫描索引树, 不需要扫描数据的树
    explain select * from departments 
    -- type 为 all 扫描整个表
    explain select * from employees;
    
  1. possible_keys

这一列用来显示查询可能使用的索引列有哪些字段, 但是在实际执行的情况, 有可能出现possible_keys有列字段, 但是实际使用的key显示为空的情况,这种情况, 可能是因为MySQL在执行优化器的时候, 认为不使用索引可能性能更好, 直接不走索引.

-- possible_keys 可以根据索引扫描, 但是key为null, 没有使用索引
explain select * from dept_manager where dept_no > 'd002'
-- 使用索引的情况
explain select * from dept_manager where dept_no = 'd002'
  1. key

这一列主要显示实际使用的列索引是哪一列
如果没有使用索引, 则该值为空

  1. key_len

这一列显示的是使用的索引的列的总长度, 主要计算的规则

  • char(n) : 如果使用的是utf-8, 则是3n长度
  • varchar(n): 如果使用的是utf-8, 则是3n+2
  • int: 4个字节的长度
  • bigint 8个字节的长度
  • date: 3个字节的长度
  1. ref

这一列显示的是key列记录在索引中, 表查找所用到的列或者常量值, 常见的有:const(常量),字段名

  1. rows

这一列显示的是MySQL估计需要扫描的行数

  1. Extra列

显示的是执行计划的一些扩展说明信息, 常见的字段有

  • Not exists

在employees和dept_emp进行关联查询的时候, 如果发现存在一个对应的emp_no, 但是在where子句中我们的判断条件是 emp_no is null, 当扫描到一条不符合条件的记录之后, 就会停止继续多次扫描

explain 
select count(1) 
from employees a 
left join dept_emp b on a.emp_no = b.emp_no 
where b.emp_no is null
  • Using index: 使用的是索引覆盖

需要查询的字段是我们的索引字段中的字段, 查询数据的时候不需要回表操作, 只需要在索引树上就可以找到对应的记录即可

-- use index 使用索引覆盖
explain select * from departments
explain select emp_no,first_name,last_name from employees
  • Using where

    explain select * from employees where emp_no  < 10004 and gender ='F'
    
  • Using index condition

根据索引树的条件进行推断,就是有一些判断条件是在索引树的列中包含的话, 就会直接在遍历索引的时候把数据查询出来, 而不是通过回表操作, 查询完数据以后再进行判断
查询的列不完全在索引列中

-- 给表salaries 添加 普通的复合索引 from_data,salary
alter table salaries add key idx_test (from_date,salary);
explain select * from salaries where from_date='1987-06-26' and  salary>60000
  • Using temporary MySQL需要创建一张临时表来处理查询。出现这种情况一般是要进行优化的,首先是想到用索引来优化。

    explain select distinct last_name from employees;
    
  • Using filesort

在查询数据的时候, 需要对查询的结果集进行排序操作, 数据小的时候, 可以在内存中进行排序, 如果数据量比较大, 就需要借助磁盘进行外部排序操作.性能比较慢

explain select * from employees order by hire_date

Profiling工具使用

profiling工具可以查询一个SQL语句的执行执行时间,通过profiling工具, 我们可以用来对比优化前和优化后的SQL性能.

开启profile

默认情况下,profile工具是处于关闭状态, 并且只是对当前会话,当会话关闭以后, profile 失效

-- 查看开启状态
select @@profiling;

image.png
值为1 表示开启状态, 值为0 表示关闭状态

-- 开启profiling 监控
set profiling = 1;

监控SQL语句

-- 监控SQL语句,我们需要运行之后才可以监控对应的SQL语句
-- 性能差的SQL
SELECT * FROM employees WHERE emp_no IN ( SELECT emp_no FROM employees WHERE emp_no = '10001' UNION SELECT emp_no FROM employees WHERE emp_no = '10002' );
-- 优化后的SQL语句
SELECT * FROM employees WHERE emp_no IN ( 10001 , 10002 );
show profiles;

image.png

trace工具

-- 建表语句
create table t6(
id int auto_increment not null,
name varchar(12),
height int,
weight int,
face int,
remark varchar(20),
primary key (id),
key idx_height (height)
);


insert into t6(name,height,weight,face) values
('zs',182,80,100),
('ls',182,80,80),
('ww',182,70,98),
('zl',182,95,95),
('zs',182,80,100),
('ls',182,80,80),
('ww',182,70,98),
('zl',182,95,95);

select * from t6

我们来分析下面的两个SQL

explain select * from t6  where height = 182

image.png

insert into t6(name,height,weight,face) values
('zs',182,80,100),
('ls',182,80,80),
('ww',182,70,98),
('zl',182,95,95);

explain select * from t6  where height = 182

image.png

开启trace

默认情况下trace是关闭的, 而且在生产环境不建议直接开启trace, 对于MySQL的性能会有一定的影响, 使用完毕后记得关闭trace命令

-- 查看trace的相关配置参数
show variables like '%trace%';

image.png
其中重要的参数:

  • optimizer_trace: 用来跟踪对应的SQL语句, enabled=off 表示关闭功能, 开启需要设置为enabled=on
    -- 开启trace 跟踪
    set optimizer_trace='enabled=on';
    set end_markers_in_json='on';
    

    跟踪分析SQL

    -- 执行SQL
    select * from t6  where height = 182 ;
    --查询分析语句
    select * from information_schema.optimizer_trace\G
    
    分析的内容说明
    {
    "steps": [
      {
       # 第一步: prepare准备阶段
        "join_preparation": {
          "select#": 1,
          "steps": [
            {
              # 进行SQL语句的格式化操作
              "expanded_query": "/* select#1 */ select `t6`.`id` AS `id`,`t6`.`name` AS `name`,`t6`.`height` AS `height`,`t6`.`weight` AS `weight`,`t6`.`face` AS `face`,`t6`.`remark` AS `remark` from `t6` where (`t6`.`height` = 182)"
            }
          ] /* steps */
        } /* join_preparation */
      },
      {
      # 第二步: SQL的优化阶段
        "join_optimization": {
          "select#": 1,
          "steps": [
            {
              # 判断条件优化
              "condition_processing": {
                # 条件类型是 where条件类型,也有可能是having条件类型
                "condition": "WHERE",
                # original_condition 原始条件类型
                "original_condition": "(`t6`.`height` = 182)",
                "steps": [
                  {
                    # 第一步优化: 等值优化
                    "transformation": "equality_propagation",
                    # 优化之后的输出结果
                    "resulting_condition": "multiple equal(182, `t6`.`height`)"
                  },
                  {
                    # 第二步优化: 常量比较优化
                    "transformation": "constant_propagation",
                    # 优化之后的输出结果
                    "resulting_condition": "multiple equal(182, `t6`.`height`)"
                  },
                  {
                    # 第二步优化: 条件移除优化, 去掉一些不必要的条件
                    "transformation": "trivial_condition_removal",
                    "resulting_condition": "multiple equal(182, `t6`.`height`)"
                  }
                ] /* steps */
              } /* condition_processing */
            },
            {
              "substitute_generated_columns": {
              } /* substitute_generated_columns */
            },
            {
               # 表的依赖分析
              "table_dependencies": [
                {
                   #表名
                  "table": "`t6`",
                  # 判断行记录是否有可能为空, 在left join 连接的被驱动表上会显示为true
                  "row_may_be_null": false,
                  # 当前的记录位: 0  
                  "map_bit": 0,
                  # 依赖的前置记录位
                  "depends_on_map_bits": [
                  ] /* depends_on_map_bits */
                }
              ] /* table_dependencies */
            },
            {
              # 使用的优化的索引
              "ref_optimizer_key_uses": [
                {
                  "table": "`t6`",
                  "field": "height",
                  "equals": "182",
                  "null_rejecting": true
                }
              ] /* ref_optimizer_key_uses */
            },
            {
              # 扫描表的行记录的一个性能评估
              "rows_estimation": [
                {
                  "table": "`t6`",
                  # 数据扫描分析
                  "range_analysis": {
                    "table_scan": {
                      # 扫描的记录数
                      "rows": 12,
                       # cost的成本值
                      "cost": 3.55
                    } /* table_scan */,
                    # 表的索引分析
                    "potential_range_indexes": [
                      {
                        # 主键索引
                        "index": "PRIMARY",
                        "usable": false,
                        "cause": "not_applicable"
                      },
                      {
                        # 普通索引
                        "index": "idx_height",
                        "usable": true,
                        # 索引的部分
                        "key_parts": [
                          "height",
                          "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 */,
                    "skip_scan_range": {
                      "potential_skip_scan_indexes": [
                        {
                          "index": "idx_height",
                          "usable": false,
                          "cause": "query_references_nonkey_column"
                        }
                      ] /* potential_skip_scan_indexes */
                    } /* skip_scan_range */,
                    # 分析索引的使用成本
                    "analyzing_range_alternatives": {
                       # range 扫描分析
                      "range_scan_alternatives": [
                        {
                           # 索引名称
                          "index": "idx_height",
                          # 扫描范围
                          "ranges": [
                            "182 <= height <= 182"
                          ] /* ranges */,
                          # 选择一种计算更准确的方式
                          "index_dives_for_eq_ranges": true,
                          # rowId是否有序
                          "rowid_ordered": true,
                          # 是否使用了mrr优化
                          "using_mrr": false,
                          # 是否只查询索引数据 
                          "index_only": false,
                          # 返回的行数
                          "rows": 12,
                          # 预估的成本
                          "cost": 4.46,
                          # 是否选择
                          "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": "`t6`",
                  # 最优的访问路径
                  "best_access_path": {
                    "considered_access_paths": [
                      {
                        # 使用索引的方式 
                        "access_type": "ref",
                        "index": "idx_height",
                        "rows": 12,
                        "cost": 1.7,
                        "chosen": true
                      },
                      {
                        #扫描表的方式
                        "rows_to_scan": 12,
                        "access_type": "scan",
                        "resulting_rows": 12,
                        "cost": 1.45,
                        "chosen": true
                      }
                    ] /* considered_access_paths */
                  } /* best_access_path */,
                  # 最终选择的方案
                  "condition_filtering_pct": 100,
                  "rows_for_plan": 12,
                  "cost_for_plan": 1.45,
                  "chosen": true
                }
              ] /* considered_execution_plans */
            },
            {
               # 优化原来的where条件
              "attaching_conditions_to_tables": {
                "original_condition": "(`t6`.`height` = 182)",
                "attached_conditions_computation": [
                ] /* attached_conditions_computation */,
                "attached_conditions_summary": [
                  {
                    "table": "`t6`",
                    "attached": "(`t6`.`height` = 182)"
                  }
                ] /* attached_conditions_summary */
              } /* attaching_conditions_to_tables */
            },
            {
              "finalizing_table_conditions": [
                {
                  "table": "`t6`",
                  "original_table_condition": "(`t6`.`height` = 182)",
                  "final_table_condition   ": "(`t6`.`height` = 182)"
                }
              ] /* finalizing_table_conditions */
            },
            {
              # 改善执行计划
              "refine_plan": [
                {
                  "table": "`t6`"
                }
              ] /* refine_plan */
            }
          ] /* steps */
        } /* join_optimization */
      },
      {
        "join_execution": {
          "select#": 1,
          "steps": [
          ] /* steps */
        } /* join_execution */
      }
    ] /* steps */
    }
    
    在我们分析完对应的执行计划之后,需要及时的关闭trace命令