第4章 EXPLAIN 执行计划详解
环境:本机 MySQL 8.0.46(
C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe)。大数据量实测库:explain_lab_big。实测脚本:experiments/explain_lab/_run_explain_lab_big.ps1(ANALYZE/TREE/JSON)、experiments/explain_lab/_run_explain_only_big.ps1(传统 EXPLAIN)原始结果:experiments/explain_lab/explain_lab_big_results.md、experiments/explain_lab/explain_lab_big_explain_only_results.md官方文档:
1. EXPLAIN 是什么
EXPLAIN 用来查看 MySQL 优化器为 SQL 选择的执行计划:会读哪些表、按什么顺序、用哪个索引、预计扫描多少行、是否需要临时表/排序等。它是 SQL 性能分析的第一工具。
1.1 语法与形式
EXPLAIN SELECT ...; -- 传统表格计划
EXPLAIN FORMAT=JSON SELECT ...; -- 详细 JSON:cost、used_columns、attached_condition 等
EXPLAIN FORMAT=TREE SELECT ...; -- 树形迭代器计划,易读执行顺序
EXPLAIN ANALYZE SELECT ...; -- 真正执行并给出 actual time/rows/loops(8.0.18+)
EXPLAIN FOR CONNECTION <process_id>; -- 查看正在运行连接的计划
| 形式 | 是否真正执行 | 输出重点 | 适用场景 |
|---|---|---|---|
EXPLAIN |
否 | 估算计划 | 日常排查首选,安全 |
EXPLAIN FORMAT=TREE |
否 | 迭代器嵌套、cost/rows | 看复杂 JOIN 执行顺序 |
EXPLAIN FORMAT=JSON |
否 | 详细成本、使用列、条件下推 | 诊断优化器决策 |
EXPLAIN ANALYZE |
是 | actual time/rows/loops + 估算 | 估算偏差、真实瓶颈定位 |
注意:
EXPLAIN ANALYZE会真实执行语句。对SELECT是真实查询;对UPDATE/DELETE要极谨慎,避免误改数据。
2. 大数据量实验环境
本章不再只用几行玩具数据,而是用一个接近业务形态的电商库 explain_lab_big,覆盖多表 JOIN、聚合、排序分页、子查询/CTE、索引对比。
2.1 数据规模
| 表 | 行数 | 说明 |
|---|---|---|
categories |
20 | 类目树 |
customers |
10,000 | 客户、城市、省份、等级、状态 |
products |
2,000 | 商品、品牌、类目、价格、状态 |
orders |
40,000 | 订单、客户、日期、状态、支付状态、金额 |
order_items |
120,000 | 订单明细,订单与商品关联 |
payments |
36,000 | 支付记录,一单一支付 |
shipments |
30,000 | 物流记录 |
reviews |
20,000 | 评论,关联订单/商品/客户 |
2.2 表结构与索引
CREATE TABLE customers (
id BIGINT UNSIGNED NOT NULL,
email VARCHAR(120) NOT NULL,
name VARCHAR(50) NOT NULL,
city VARCHAR(30) NOT NULL,
province VARCHAR(30) NOT NULL,
level TINYINT UNSIGNED NOT NULL, -- 1普通 2银 3金 4钻
status VARCHAR(20) NOT NULL, -- active/inactive/banned
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uk_email(email),
KEY idx_city(city),
KEY idx_level_status(level, status),
KEY idx_created(created_at)
) ENGINE=InnoDB;
CREATE TABLE orders (
id BIGINT UNSIGNED NOT NULL,
customer_id BIGINT UNSIGNED NOT NULL,
order_no VARCHAR(32) NOT NULL,
status VARCHAR(20) NOT NULL, -- created/paid/shipped/done/cancelled
pay_status VARCHAR(20) NOT NULL, -- unpaid/paid/refunded
order_date DATE NOT NULL,
province VARCHAR(30) NOT NULL,
amount DECIMAL(12,2) NOT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uk_order_no(order_no),
KEY idx_customer_date(customer_id, order_date),
KEY idx_date_status(order_date, status),
KEY idx_pay_status(pay_status),
KEY idx_province_date(province, order_date)
) ENGINE=InnoDB;
其他关键索引:
| 表 | 关键索引 | 用途 |
|---|---|---|
products |
idx_category, idx_brand_status, idx_price |
品牌/类目过滤、价格排序 |
order_items |
idx_order_id, idx_product_id |
订单->明细、商品->明细 |
payments |
uk_order_id, idx_method_status, idx_paid_at |
订单支付关联 |
shipments |
uk_order_id, idx_ship_status |
物流关联 |
reviews |
idx_product_rating, idx_customer, idx_created |
商品评论/评分 |
2.3 关系图
3. EXPLAIN 输出列速查
| 列 | 含义 | 重点看什么 |
|---|---|---|
id |
SELECT 标识符 | 大 id 通常先执行;同 id 常为同一层 join |
select_type |
查询类型 | SIMPLE/PRIMARY/DERIVED/MATERIALIZED/UNION 等 |
table |
访问表/派生表 | <derivedN>、物化表要注意 |
type |
访问类型 | system>const>eq_ref>ref>range>index>ALL(简化) |
possible_keys |
候选索引 | 有候选但没选,说明优化器认为代价更高 |
key |
实际索引 | NULL 通常表示没走索引 |
key_len |
使用的索引长度 | 联合索引用了几列 |
ref |
与索引比较的值 | const、db.table.col、func |
rows |
估算检查行数 | InnoDB 估算,可能偏差 |
filtered |
过滤百分比 | rows * filtered% 估算传给下一步的行数 |
Extra |
额外动作 | Using index 好;Using filesort/temporary 警惕;Using where 中性 |
3.1 type 快速判断
| type | 含义 | 常见信号 |
|---|---|---|
const |
主键/唯一索引等值,最多一行 | 命中非常明确 |
eq_ref |
join 时被驱动表主键/唯一索引等值 | 每次最多匹配一行 |
ref |
非唯一索引等值 | 可能多行 |
range |
索引范围扫描 | BETWEEN、>=、IN、前缀 LIKE |
index |
全索引扫描 | 比 ALL 轻,但仍是全扫描 |
ALL |
全表扫描 | 大表要重点排查 |
3.2 EXPLAIN ANALYZE 怎么读
-> Nested loop inner join (cost=... rows=...) (actual time=first..last rows=N loops=L)
| 字段 | 含义 |
|---|---|
cost |
优化器估算成本 |
rows |
优化器估算行数 |
actual time=first..last |
第一行返回时间..全部返回时间(ms) |
actual rows |
实际行数 |
loops |
该迭代器执行次数 |
读树时从最内层/最先缩进的源节点往外看:先看谁产出行,再看行如何被 join/filter/sort/limit。
4. Case 1:6表 JOIN + 过滤 + 排序 + 分页
4.1 SQL
EXPLAIN ANALYZE
SELECT
o.id, o.order_no, o.order_date, o.amount, o.status,
c.name AS customer_name, c.city,
p.name AS product_name, cat.name AS category_name,
pay.pay_method, pay.pay_status
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
JOIN categories cat ON cat.id = p.category_id
JOIN payments pay ON pay.order_id = o.id
WHERE o.order_date >= '2025-10-01' AND o.order_date < '2025-11-01'
AND o.status = 'paid'
AND c.province = 'Shanghai'
AND p.brand = 'Apple'
AND pay.pay_status = 'success'
ORDER BY o.order_date DESC, o.id DESC
LIMIT 20;
4.2 传统 EXPLAIN
+----+-------------+-------+------------+--------+-------------------------------------------+-----------------+---------+-------------------------------+------+----------+--------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+-------------------------------------------+-----------------+---------+-------------------------------+------+----------+--------------------------------------------+
| 1 | SIMPLE | o | NULL | range | PRIMARY,idx_customer_date,idx_date_status | idx_date_status | 85 | NULL | 3325 | 10.00 | Using index condition; Backward index scan |
| 1 | SIMPLE | c | NULL | eq_ref | PRIMARY | PRIMARY | 8 | explain_lab_big.o.customer_id | 1 | 10.00 | Using where |
| 1 | SIMPLE | pay | NULL | eq_ref | uk_order_id | uk_order_id | 8 | explain_lab_big.o.id | 1 | 10.00 | Using where |
| 1 | SIMPLE | oi | NULL | ref | idx_order_id,idx_product_id | idx_order_id | 8 | explain_lab_big.o.id | 2 | 100.00 | NULL |
| 1 | SIMPLE | p | NULL | eq_ref | PRIMARY,idx_category,idx_brand_status | PRIMARY | 8 | explain_lab_big.oi.product_id | 1 | 10.00 | Using where |
| 1 | SIMPLE | cat | NULL | eq_ref | PRIMARY | PRIMARY | 4 | explain_lab_big.p.category_id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+--------+-------------------------------------------+-----------------+---------+-------------------------------+------+----------+--------------------------------------------+
读传统 EXPLAIN 的关键点:
o先走:type=range,key=idx_date_status,key_len=85说明(order_date,status)两列都被用到(DATE 3B + VARCHAR(20) utf8mb4 NOT NULL 82B);Backward index scan对应ORDER BY ... DESC。rows=3325, filtered=10%是估算,不是实际值;真实 ANLYZE 显示扫出 1690 行。c/pay/p都是eq_ref但带Using where,说明主键/唯一键定位后还要做非索引条件过滤。
4.3 EXPLAIN ANALYZE(实际执行)
-> Limit: 20 row(s) (actual time=37.6..37.6 rows=0 loops=1)
-> Nested loop inner join (actual time=37.6..37.6 rows=0 loops=1)
-> Nested loop inner join (actual time=37.6..37.6 rows=0 loops=1)
-> Nested loop inner join (actual time=2.66..35.2 rows=882 loops=1)
-> Nested loop inner join (actual time=2.61..28.1 rows=294 loops=1)
-> Nested loop inner join (actual time=2.52..24.4 rows=327 loops=1)
-> Index range scan on o using idx_date_status over (... 'paid') (reverse)
(actual time=1.68..14.4 rows=1690 loops=1)
-> Filter: (c.province = 'Shanghai') (actual rows=0.193 loops=1690)
-> Single-row index lookup on c using PRIMARY (id=o.customer_id)
-> Filter: (pay.pay_status = 'success') (actual rows=0.899 loops=327)
-> Single-row index lookup on pay using uk_order_id (order_id=o.id)
-> Index lookup on oi using idx_order_id (order_id=o.id) (actual rows=3 loops=294)
-> Filter: (p.brand = 'Apple') (actual rows=0 loops=882)
-> Single-row index lookup on p using PRIMARY (id=oi.product_id)
-> Single-row index lookup on cat using PRIMARY (id=p.category_id) (never executed)
4.4 怎么读
关键观察:
- 驱动表选得合理:
orders用idx_date_status(order_date,status)做反向范围扫描,同时满足日期范围、status='paid'和ORDER BY ... DESC LIMIT 20的方向需求。 loops很说明问题:c被查 1690 次,pay327 次,p882 次。嵌套循环里,内层 loops 大往往是成本来源。- 过滤发生在取行后:
c.province='Shanghai'和p.brand='Apple'不是索引前导条件,只能先 PK 查到行再 Filter。尤其p.brand='Apple'把 882 行全部过滤掉,导致cat节点never executed。 - LIMIT 不保证提前结束:虽然有
LIMIT 20,但过滤条件太苛刻,直到上游被过滤光也凑不够 20 行。
优化思路(方向,不是本次实测):如果这类查询频繁,可评估 orders(status, order_date, id) 或覆盖索引、customers(province,id)、products(brand,id,category_id,name) 等,让过滤更早、更少回表;但要结合写入成本和真实业务。
5. Case 2:同一条 SQL,加索引前后对比
5.1 SQL
EXPLAIN ANALYZE
SELECT c.name, COUNT(*) cnt, SUM(o.amount) total
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.city = 'Beijing'
AND o.pay_status = 'paid'
AND o.amount > 500
GROUP BY c.id, c.name
ORDER BY total DESC
LIMIT 10;
5.2 Case 2A:传统 EXPLAIN
+----+-------------+-------+------------+------+----------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+----------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
| 1 | SIMPLE | c | NULL | ref | PRIMARY,idx_city | idx_city | 122 | const | 1000 | 100.00 | Using temporary; Using filesort |
| 1 | SIMPLE | o | NULL | ref | idx_customer_date,idx_pay_status | idx_customer_date | 8 | explain_lab_big.c.id | 4 | 16.66 | Using where |
+----+-------------+-------+------------+------+----------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
5.3 Case 2A:EXPLAIN ANALYZE
-> Limit: 10 row(s) (actual time=27.2..27.2 rows=0 loops=1)
-> Sort: total DESC, limit input to 10 row(s) per chunk
-> Table scan on <temporary>
-> Aggregate using temporary table
-> Nested loop inner join (cost=1630 rows=694) (actual time=26.9..26.9 rows=0 loops=1)
-> Index lookup on c using idx_city (city='Beijing') (rows=1000 loops=1)
-> Filter: ((o.pay_status = 'paid') and (o.amount > 500.00)) (rows=0 loops=1000)
-> Index lookup on o using idx_customer_date (customer_id=c.id) (rows=4 loops=1000)
5.4 Case 2B:加 idx_paystatus_amount(pay_status, amount) 后
CREATE INDEX idx_paystatus_amount ON orders(pay_status, amount);
-- 再次 EXPLAIN / EXPLAIN ANALYZE 同一 SQL
-- 然后 DROP INDEX idx_paystatus_amount;
传统 EXPLAIN:
+----+-------------+-------+------------+------+-------------------------------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+-------------------------------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
| 1 | SIMPLE | c | NULL | ref | PRIMARY,idx_city | idx_city | 122 | const | 1000 | 100.00 | Using temporary; Using filesort |
| 1 | SIMPLE | o | NULL | ref | idx_customer_date,idx_pay_status,idx_paystatus_amount | idx_customer_date | 8 | explain_lab_big.c.id | 4 | 16.66 | Using where |
+----+-------------+-------+------------+------+-------------------------------------------------------+-------------------+---------+----------------------+------+----------+---------------------------------+
EXPLAIN ANALYZE:
-> Limit: 10 row(s) (actual time=14.7..14.7 rows=0 loops=1)
-> Sort: total DESC, limit input to 10 row(s) per chunk
-> Table scan on <temporary>
-> Aggregate using temporary table
-> Nested loop inner join (cost=1630 rows=694) (actual time=14.5..14.5 rows=0 loops=1)
-> Index lookup on c using idx_city (city='Beijing') (rows=1000)
-> Filter: ((o.pay_status = 'paid') and (o.amount > 500.00)) (rows=0 loops=1000)
-> Index lookup on o using idx_customer_date (customer_id=c.id) (rows=4 loops=1000)
5.5 分析
| 版本 | orders 访问 | actual time | 结果 |
|---|---|---|---|
| 2A | idx_customer_date,取4行再过滤 |
~27.2ms | 0行 |
| 2B | 仍然 idx_customer_date |
~14.7ms | 0行 |
这个结果很有教学价值:
- 加了索引,不代表优化器一定用。优化器基于成本选计划。这个 SQL 从
city='Beijing'的 1000 个客户出发,每个客户平均 4 单,走customer_id定位非常直接;而pay_status='paid' AND amount>500选择性未必足够好,且不能同时利用customer_id连接路径。 - 2B 变快不等于计划变好。计划形状没变,耗时波动可能来自缓存、运行时状态等。判断优化不能只看一次时间,要看计划、loops、实际行数和多次采样。
- 正确结论:索引设计要贴合查询模式。若查询是“先按客户找订单再过滤”,
(customer_id,pay_status,amount)或(customer_id,amount)可能更贴合;若查询是“先按支付状态和金额筛订单再找客户”,(pay_status,amount,customer_id)才可能被选中。
6. Case 3:6表聚合报表,GROUP BY + HAVING
6.1 SQL
EXPLAIN ANALYZE
SELECT
cat.name AS category_name,
p.brand,
COUNT(DISTINCT o.id) AS order_cnt,
SUM(oi.subtotal) AS gmv,
AVG(r.rating) AS avg_rating
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
JOIN categories cat ON cat.id = p.category_id
LEFT JOIN payments pay ON pay.order_id = o.id
LEFT JOIN reviews r ON r.order_id = o.id AND r.product_id = p.id
WHERE o.order_date >= '2025-07-01' AND o.order_date < '2025-10-01'
AND o.status IN ('paid','shipped','done')
AND pay.pay_status = 'success'
GROUP BY cat.id, cat.name, p.brand
HAVING SUM(oi.subtotal) > 50000
ORDER BY gmv DESC
LIMIT 15;
6.2 传统 EXPLAIN
+----+-------------+-------+------------+--------+-----------------------------+--------------------+---------+-------------------------------+-------+----------+----------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+-----------------------------+--------------------+---------+-------------------------------+-------+----------+----------------------------------------------+
| 1 | SIMPLE | pay | NULL | ALL | uk_order_id | NULL | NULL | NULL | 35997 | 10.00 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | o | NULL | eq_ref | PRIMARY,idx_date_status | PRIMARY | 8 | explain_lab_big.pay.order_id | 1 | 13.90 | Using where |
| 1 | SIMPLE | oi | NULL | ref | idx_order_id,idx_product_id | idx_order_id | 8 | explain_lab_big.pay.order_id | 2 | 100.00 | NULL |
| 1 | SIMPLE | p | NULL | eq_ref | PRIMARY,idx_category | PRIMARY | 8 | explain_lab_big.oi.product_id | 1 | 100.00 | NULL |
| 1 | SIMPLE | cat | NULL | eq_ref | PRIMARY | PRIMARY | 4 | explain_lab_big.p.category_id | 1 | 100.00 | NULL |
| 1 | SIMPLE | r | NULL | ref | idx_product_rating | idx_product_rating | 8 | explain_lab_big.oi.product_id | 9 | 100.00 | Using where |
+----+-------------+-------+------------+--------+-----------------------------+--------------------+---------+-------------------------------+-------+----------+----------------------------------------------+
6.3 EXPLAIN ANALYZE(实际执行)
-> Limit: 15 row(s) (actual time=773..773 rows=14 loops=1)
-> Sort: gmv DESC
-> Filter: (sum(order_items.subtotal) > 50000) (rows=14)
-> Stream results
-> Group aggregate: count(distinct o.id), sum(oi.subtotal), avg(r.rating)
-> Sort: cat.id, cat.name, p.brand (actual time=757..760 rows=19068)
-> Nested loop left join reviews
-> Nested loop inner join categories
-> Nested loop inner join products
-> Nested loop inner join order_items
-> Nested loop inner join orders
-> Filter: pay.pay_status='success' (rows=28800)
-> Table scan on pay (rows=36000)
-> Filter: date/status on o via PK lookup (rows=0.221 loops=28800)
-> Index lookup oi.idx_order_id (rows=3 loops=6356)
-> Single-row PK lookup p
-> Single-row PK lookup cat
-> Index lookup r.idx_product_rating (rows=10 loops=19068)
6.4 分析
- 驱动表出人意料是
payments全表扫描:优化器先扫payments36k 行,过滤pay_status='success'得 28.8k,再用o.PRIMARY回查订单并过滤日期/状态。说明在当前统计和索引下,它认为这条路成本可接受。 - LEFT JOIN 被 WHERE 条件“半实化”:虽然写的是
LEFT JOIN payments ...,但WHERE pay.pay_status='success'要求 pay 非空且成功,语义上接近 INNER JOIN。写 SQL 时要注意这类条件会改变外连接语义。 - 聚合代价明显:中间产出 19,068 行,先按分组键排序,再做 group aggregate,最后 HAVING 过滤到 14 行。
actual time大头在 7xx ms。 reviews的 join 放大:r.idx_product_rating每个 product 平均匹配 10 行,loops=19068,是典型的“维度放大”。如果只需要订单维度评价,应先在订单/商品维度聚合再 join。
7. Case 4:派生表 vs CTE
7.1 SQL
-- 4A 派生表
EXPLAIN ANALYZE
SELECT c.id, c.name, t.order_cnt, t.total_amount
FROM customers c
JOIN (
SELECT customer_id, COUNT(*) order_cnt, SUM(amount) total_amount
FROM orders
WHERE order_date >= '2025-01-01' AND status = 'paid'
GROUP BY customer_id
) t ON t.customer_id = c.id
WHERE c.level >= 3 AND c.status = 'active'
ORDER BY t.total_amount DESC
LIMIT 20;
-- 4B CTE
EXPLAIN ANALYZE
WITH paid_orders AS (
SELECT customer_id, COUNT(*) order_cnt, SUM(amount) total_amount
FROM orders
WHERE order_date >= '2025-01-01' AND status = 'paid'
GROUP BY customer_id
)
SELECT c.id, c.name, p.order_cnt, p.total_amount
FROM customers c
JOIN paid_orders p ON p.customer_id = c.id
WHERE c.level >= 3 AND c.status = 'active'
ORDER BY p.total_amount DESC
LIMIT 20;
7.2 传统 EXPLAIN
两者传统计划形状一致:
+----+-------------+------------+------------+--------+-----------------------------------+-------------------+---------+---------------+-------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------+------------+--------+-----------------------------------+-------------------+---------+---------------+-------+----------+----------------+
| 1 | PRIMARY | <derived2> | NULL | ALL | NULL | NULL | NULL | NULL | 1999 | 100.00 | Using filesort |
| 1 | PRIMARY | c | NULL | eq_ref | PRIMARY,idx_level_status | PRIMARY | 8 | t.customer_id | 1 | 5.00 | Using where |
| 2 | DERIVED | orders | NULL | index | idx_customer_date,idx_date_status | idx_customer_date | 11 | NULL | 39996 | 5.00 | Using where |
+----+-------------+------------+------------+--------+-----------------------------------+-------------------+---------+---------------+-------+----------+----------------+
7.3 EXPLAIN ANALYZE
-> Limit 20
-> Nested loop inner join
-> Sort: total_amount DESC
-> Table scan on t/p
-> Materialize / Materialize CTE paid_orders (rows=5000)
-> Group aggregate
-> Filter: status='paid' and order_date >= ...
-> Index scan on orders using idx_customer_date (rows=40000, actual filtered to 20000)
-> Filter: c.level>=3 and c.status='active'
-> Single-row PK lookup on c
| 版本 | 物化行数 | 总时间 |
|---|---|---|
| 派生表 4A | 5000 | ~99ms |
| CTE 4B | 5000 | ~101ms |
7.4 结论
- 这组查询里,CTE 不比派生表神奇。MySQL 8.0 对非递归 CTE 可能合并或物化;本例都物化了中间聚合结果。
- 物化的代价是先把 5000 行聚合结果存起来,再排序取前 20,最后回查客户。
- 选 CTE 还是派生表,优先看可读性、复用性和实际计划,不要迷信“CTE 更快/更慢”。
8. Case 5:排序分页,filesort vs 索引顺序
8.1 Case 5A:按 amount 排序
EXPLAIN / EXPLAIN ANALYZE
SELECT o.id, o.order_no, o.order_date, o.amount, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
ORDER BY o.amount DESC
LIMIT 20;
传统 EXPLAIN:
+----+-------------+-------+------------+--------+-------------------+---------+---------+-------------------------------+-------+----------+-----------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+-------------------+---------+---------+-------------------------------+-------+----------+-----------------------------+
| 1 | SIMPLE | o | NULL | ALL | idx_customer_date | NULL | NULL | NULL | 39996 | 10.00 | Using where; Using filesort |
| 1 | SIMPLE | c | NULL | eq_ref | PRIMARY | PRIMARY | 8 | explain_lab_big.o.customer_id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+--------+-------------------+---------+---------+-------------------------------+-------+----------+-----------------------------+
EXPLAIN ANALYZE:
-> Limit: 20 row(s) (actual time=42.1..42.1 rows=20 loops=1)
-> Nested loop inner join
-> Sort: o.amount DESC (actual time=41.9..42 rows=20)
-> Filter: (o.status = 'paid') (rows=20000)
-> Table scan on o (rows=40000)
-> Single-row index lookup on c using PRIMARY (id=o.customer_id) (loops=20)
观察:虽然 orders 有 idx_amount,优化器仍选了全表扫 + Filter + Sort。原因是 status='paid' 不是通过该索引前导过滤,走 amount 索引可能需要大量回表/过滤,优化器评估全表更划算。
8.2 Case 5B:按 (order_date, id) 排序
EXPLAIN / EXPLAIN ANALYZE
SELECT o.id, o.order_no, o.order_date, o.amount, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
ORDER BY o.order_date DESC, o.id DESC
LIMIT 20;
传统 EXPLAIN:
+----+-------------+-------+------------+--------+-------------------+-----------------+---------+-------------------------------+------+----------+----------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+-------------------+-----------------+---------+-------------------------------+------+----------+----------------------------------+
| 1 | SIMPLE | o | NULL | index | idx_customer_date | idx_date_status | 85 | NULL | 20 | 10.00 | Using where; Backward index scan |
| 1 | SIMPLE | c | NULL | eq_ref | PRIMARY | PRIMARY | 8 | explain_lab_big.o.customer_id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+--------+-------------------+-----------------+---------+-------------------------------+------+----------+----------------------------------+
EXPLAIN ANALYZE:
-> Limit: 20 row(s) (actual time=0.25..0.397 rows=20 loops=1)
-> Nested loop inner join
-> Filter: (o.status = 'paid') (actual rows=20 loops=1)
-> Index scan on o using idx_date_status (reverse) (rows=74)
-> Single-row index lookup on c using PRIMARY (loops=20)
| 版本 | orders 访问 | 排序 | actual time |
|---|---|---|---|
5A ORDER BY amount DESC |
全表 40k -> 过滤 20k | Sort | ~42.1ms |
5B ORDER BY order_date DESC, id DESC |
idx_date_status 反向扫 74 行 |
利用索引顺序 | ~0.40ms |
结论:排序能否消掉 filesort/显式 sort,关键看 ORDER BY 能否对齐索引顺序,并且 WHERE 条件与索引兼容。这也是分页查询常见优化点。
9. Case 6:函数/表达式导致索引失效的典型场景
9.1 Case 6A:对列使用函数
EXPLAIN / EXPLAIN ANALYZE
SELECT * FROM orders
WHERE DATE(created_at) = '2025-06-01'
AND status = 'paid';
传统 EXPLAIN:
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
| 1 | SIMPLE | orders | NULL | ALL | NULL | NULL | NULL | NULL | 39996 | 10.00 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
EXPLAIN ANALYZE:
-> Filter: ((orders.status = 'paid') and (cast(orders.created_at as date) = '2025-06-01'))
(actual time=32.2..32.2 rows=0 loops=1)
-> Table scan on orders (cost=4072 rows=39996) (actual time=0.294..26.1 rows=40000 loops=1)
9.2 Case 6B:改写为范围条件
EXPLAIN / EXPLAIN ANALYZE
SELECT * FROM orders
WHERE created_at >= '2025-06-01 00:00:00'
AND created_at < '2025-06-02 00:00:00'
AND status = 'paid';
传统 EXPLAIN:
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
| 1 | SIMPLE | orders | NULL | ALL | NULL | NULL | NULL | NULL | 39996 | 1.11 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+-------+----------+-------------+
EXPLAIN ANALYZE:
-> Filter: ((orders.status = 'paid') and (orders.created_at >= TIMESTAMP'2025-06-01 00:00:00') and (orders.created_at < ...))
(actual time=28.7..28.7 rows=0 loops=1)
-> Table scan on orders (cost=4072 rows=39996) (actual time=0.117..23.1 rows=40000 loops=1)
9.3 分析
- 6A 对
created_at使用DATE(),优化器无法直接用created_at的有序索引范围定位,只能扫表后逐行计算。 - 6B 改成范围查询,语义等价且对索引友好。但本次仍然全表扫描,原因是
orders上没有created_at单列索引或(status, created_at)复合索引;优化器没有可用索引可选。 - 这说明两个层面的问题要分开看:
- 写法是否 SARGable(可搜索参数化):6B 是。
- 是否有合适索引:本例没有,所以仍 ALL。
如果要优化 6B,可评估 INDEX(status, created_at) 或 INDEX(created_at),再看实际计划和写入代价。
10. Case 7:传统 / TREE / JSON 怎么配合看
同一条 4 表 JOIN:
SELECT o.id, o.order_no, c.name, p.name AS product_name
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE c.city='Beijing' AND o.status='paid'
LIMIT 10;
10.1 传统 EXPLAIN
id select_type table type key key_len ref rows filtered Extra
1 SIMPLE c ref idx_city 122 const 1000 100.00 NULL
1 SIMPLE o ref idx_customer_date 8 explain_lab_big.c.id 4 10.00 Using where
1 SIMPLE oi ref idx_order_id 8 explain_lab_big.o.id 2 100.00 NULL
1 SIMPLE p eq_ref PRIMARY 8 explain_lab_big.oi.product_id 1 100.00 NULL
适合快速看:访问类型、选了哪个 key、ref、rows、filtered、Extra。
10.2 FORMAT=TREE
-> Limit: 10 row(s) (cost=2501 rows=10)
-> Nested loop inner join (cost=2501 rows=1245)
-> Nested loop inner join (cost=2066 rows=1245)
-> Nested loop inner join (cost=1630 rows=416)
-> Index lookup on c using idx_city (city='Beijing') (cost=173 rows=1000)
-> Filter: (o.status = 'paid') (cost=1.04 rows=0.416)
-> Index lookup on o using idx_customer_date (customer_id=c.id)
-> Index lookup on oi using idx_order_id (order_id=o.id)
-> Single-row index lookup on p using PRIMARY (id=oi.product_id)
适合看执行顺序和嵌套结构:从内到外,先 c,再 o,再 oi,再 p。
10.3 FORMAT=JSON
{
"query_block": {
"select_id": 1,
"cost_info": { "query_cost": "2501.23" },
"nested_loop": [
{
"table": {
"table_name": "c",
"access_type": "ref",
"key": "idx_city",
"rows_examined_per_scan": 1000,
"rows_produced_per_join": 1000,
"filtered": "100.00",
"cost_info": { "read_cost": "72.75", "eval_cost": "100.00", "prefix_cost": "172.75", "data_read_per_join": "1000K" }
}
}
]
}
}
适合看优化器成本细节:query_cost、prefix_cost、read_cost、data_read_per_join、used_columns、attached_condition。
11. 索引下推(ICP, Index Condition Pushdown)
索引下推是 MySQL 5.6+ 引入、MySQL 8.0 常见的优化:把能用索引判断的 WHERE 条件下推到存储引擎层,在二级索引记录上先过滤,减少回表和 Server 层判断。
11.1 不下推 vs 下推
11.2 识别信号
| 位置 | 信号 | 含义 |
|---|---|---|
传统 EXPLAIN Extra |
Using index condition |
使用了 ICP |
EXPLAIN FORMAT=TREE/ANALYZE |
Index ... with index condition: (...) |
计划中显式展示下推条件 |
EXPLAIN FORMAT=JSON |
index_condition |
JSON 中有下推条件字段 |
11.3 本章实测中的 ICP
Case 1 的驱动表 orders:
EXPLAIN:
type=range, key=idx_date_status, key_len=85, rows=3325, filtered=10.00
Extra=Using index condition; Backward index scan
EXPLAIN ANALYZE:
Index range scan on o using idx_date_status over (...) (reverse),
with index condition: ((o.`status` = 'paid') and (o.order_date >= DATE'2025-10-01') and (o.order_date < DATE'2025-11-01'))
idx_date_status(order_date,status) 中,order_date 范围扫描后,status='paid' 仍可作为索引条件下推,在索引层先过滤,减少不必要回表。
11.4 什么时候看不到 ICP
- 覆盖索引:不需要回表时常见
Using index,ICP 价值不大。 - 条件不能用索引判断:例如对列做函数、类型不匹配导致索引不可用。
- 聚簇索引/主键直接定位:ICP 主要针对二级索引回表场景。
- 优化器认为收益不大:是否下推由优化器成本决定。
-- 查看/关闭/开启(会话或全局)
SET optimizer_switch='index_condition_pushdown=off';
SET optimizer_switch='index_condition_pushdown=on';
实战解读:看到
Using index condition是好信号,但不是“已经最优”。仍要看rows/filtered/actual rows/loops,判断过滤是否足够早、索引是否该改成更匹配的复合索引。
12. optimizer trace / FORCE INDEX / ANALYZE TABLE
12.1 optimizer trace:看优化器为什么这么选
SET optimizer_trace='enabled=on';
SET optimizer_trace_max_mem_size=1048576;
SELECT * FROM t WHERE a=10 AND b=20;
SELECT trace FROM information_schema.OPTIMIZER_TRACE\G
SET optimizer_trace='enabled=off';
本机实测(experiments/optimizer_trace_lab/)可看到关键决策:
ref_optimizer_key_uses: a=10, b=20, (a,b)
range_scan_alternatives:
idx_a rows=100 cost=35.26
idx_b rows=10 cost=3.76
idx_ab rows=1 cost=0.61 chosen=true
best_access_path:
ref idx_ab rows=1 cost=0.35 chosen=true
用途:排查“为什么没走我想要的索引”;看 range/ref/row estimate/cost。
12.2 FORCE INDEX / IGNORE INDEX:诊断,不要当常规药
EXPLAIN SELECT * FROM t FORCE INDEX(idx_a) WHERE a=10 AND b BETWEEN 10 AND 30;
EXPLAIN SELECT * FROM t IGNORE INDEX(idx_ab) WHERE a=10 AND b BETWEEN 10 AND 30;
本机实测:
| 计划 | key | rows | Extra | actual |
|---|---|---|---|---|
| 默认 | idx_ab |
10 | Using index condition |
0.066ms, rows=10 |
FORCE INDEX(idx_a) |
idx_a |
102 | Using where |
0.219ms, rows=10, loops=1,内层扫100行 |
IGNORE INDEX(idx_ab) |
idx_a |
100 | Using where |
类似 idx_a |
结论:强制索引可证明“走别的索引更差”,但不应长期写死在业务 SQL;统计信息变化后可能适得其反。
12.3 ANALYZE TABLE
ANALYZE TABLE 更新索引统计信息(InnoDB 采样),帮助优化器估算 rows/cardinality。数据分布大幅变化后,如果计划异常,可先 ANALYZE TABLE 再看 EXPLAIN。
13. 实战排查清单
- 先看大表怎么被访问:
ALL/大范围index/巨大loops是优先信号。 - 看连接键有没有索引:join 内层没索引会放大 loops。
- 看过滤发生在哪里:
Using where在回表后过滤,代价可能高;能下推到索引或复合索引更好。 - 看排序/分组:
Using filesort、Using temporary不一定致命,但大数据量要警惕。 - 看估算 vs 实际:
EXPLAIN ANALYZE的rows/loops/actual time比单纯rows可靠。 - 加索引后复测:Case 2 证明“加了索引不代表会用”。必须对比计划。
- 别只看 SQL,看语义:Case 3 里
LEFT JOIN ... WHERE pay.pay_status='success'实际把外连接变成内连接语义。
14. 本章思考题(待测)
| # | 问题 | 参考答案 | 你的掌握 |
|---|---|---|---|
| Q1 | Case 1 中 cat 为什么是 never executed? |
上游 p.brand='Apple' 过滤后实际 0 行,嵌套循环内层没有输入行,因此 cat 不需要执行 |
待测 |
| Q2 | Case 2 加了 idx_paystatus_amount 为什么没被使用? |
优化器基于成本选择计划;当前查询从 city='Beijing' 的 1000 客户驱动,走 idx_customer_date 按 customer_id 定位更直接,新索引不能同时服务 join 路径 |
待测 |
| Q3 | Case 5A 有 idx_amount 为什么还全表排序? |
WHERE status='paid' 与 ORDER BY amount DESC 不能很好地复用同一索引顺序;走 amount 索引可能大量回表再过滤,优化器评估全表+sort 成本更低 |
待测 |
| Q4 | Case 6B 已改成范围查询,为什么还是 ALL? | 写法已 SARGable,但 orders 没有 created_at/(status,created_at) 可用索引,优化器无索引可走 |
待测 |
| Q5 | EXPLAIN ANALYZE 的 loops=1000 说明什么? |
该迭代器被执行了 1000 次;嵌套循环中内层 loops 大通常意味着驱动行多或连接放大,应关注连接条件和索引 | 待测 |
| Q6 | Extra=Using index condition 是什么意思?和 Using index 有什么区别? |
Using index condition 表示 ICP:存储引擎层先用索引条件过滤,减少回表;Using index 表示覆盖索引,查询列都在索引中,无需回表 |
待测 |
评论