Skip to content

MySQL之TRACE

1. 简介

MySQL5.6版本开始,推出了对SQL的跟踪工具trace,通过使用trace,用户可以查看MySQL优化器对SQL语句的分析结果,以及生成了怎样的执行计划。

2. 作用

对SQL跟踪,可以知道SQL是如何执行的,trace工具主要看的是MySQL大致的优化和计算成本过程,比EXPLAIN更强大。

3. trace开关

  1. 开启trace工具
sql
set session optimizer_trace="enabled=on",end_markers_in_json=on;
  1. 关闭trace工具
sql
set session optimizer_trace="enabled=off";

提示

开启trace工具会影响mysql性能,所以只能临时分析sql使用,用完之后立即关闭。

4. trace的使用

sql
-- 业务SQL
SELECT position FROM employees  WHERE age >23  ;
 
-- 查询优化器分析结果
SELECT * FROM information_schema.OPTIMIZER_TRACE;

只要查看其中的TRACE列: Alt text 优化器分析结果总共分为三步,如下图: Alt text

4.1 SQL准备阶段

对SQL进行格式化

4.2 SQL分析、优化阶段

Alt text 主要分析第二阶段,具体的分组已通过注释在代码中声明,主要有:所有索引分析,全表扫描分析,最优方案分析。最终选择依据是各个方案的预估耗时(即:cost)

json
    /* 第二阶段:SQL优化阶段 */
    {
      "join_optimization": {
        "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 */
          },
 
          /* 核心:预估表的访问成本,通过预估的cost,决定使用那种优化策略 */
          {
            "rows_estimation": [
              {
                "table": "`employees`",
 
                "range_analysis": {
                  
                  /* 全表扫描情况 */
                  "table_scan": {
                    "rows": 100140, /* 扫描行数*/
                    "cost": 20383 /* 查询成本*/
                  } /* 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 by 或 distinct 用到的索引 */
                  "group_index_range": {
                    "chosen": false, /* 未使用 */
                    "cause": "not_group_by_or_distinct" /* 原因:不是group by 或 distinct */
                  } /* group_index_range */,
 
                  /* 分析各个备选方案 */
                  "analyzing_range_alternatives": {
                    "range_scan_alternatives": [
                      {
                        "index": "idx_name_age_position",
                        "ranges": [
                          "a < name"
                        ] /* ranges */,
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,  /* 使用该索引获取的记录是否按照主键排序 */
                        "using_mrr": false,
                        "index_only": false, /* 是否使用覆盖索引 */
                        "rows": 50070,   /* 预估索引扫描行数 */
                        "cost": 60085,   /* 索引使用成本 */
                        "chosen": false, /* 是否选择该索引 */
                        "cause": "cost"  /* 原因: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": 100140,
                      "access_type": "scan", /* 访问类型:为scan,全表扫描 */
                      "resulting_rows": 100140,
                      "cost": 20381, /* 预估耗时 */
                      "chosen": true
                    }
                  ] /* considered_access_paths */
                } /* best_access_path */,
 
                "condition_filtering_pct": 100,
                "rows_for_plan": 100140,
                "cost_for_plan": 20381,
                "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 */
          },
          {
            "refine_plan": [
              {
                "table": "`employees`"
              }
            ] /* refine_plan */
          }
        ] /* steps */
      } /* join_optimization */
    },

经上述结果分析可知,根据当前表的索引(主键索引、组合索引)对比,可能采取组合索引进行查询;再预估全表扫描结果,全表扫描的cost比组合索引的cost小,mysql即判断全表扫描比组合索引效率更高,最终执行方案为全表扫描。