mysql 优化查询逻辑, sql调优.
explain命令(8.0以下)
简介:EXPLAIN 命令可以模拟 MySQL 优化器如何执行 SQL 查询,并显示详细的执行计划
使用方法:
EXPLAIN SELECT * FROM your_table WHERE column_name = 'value';
例子:
EXPLAIN
SELECT o.order_id, c.customer_name, p.product_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN products p ON o.product_id = p.product_id
WHERE c.country = 'USA' AND o.order_date >= '2023-01-01';
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | c | NULL | ref | PRIMARY,idx_country | idx_country | 103 | const | 50 | 100.00 | Using index |
| 1 | SIMPLE | o | NULL | ref | idx_customer,idx_product | idx_customer | 5 | db.c.customer_id | 100 | 50.00 | Using where |
| 1 | SIMPLE | p | NULL | eq_ref | PRIMARY | PRIMARY | 4 | db.o.product_id | 1 | 100.00 | NULL |
第一行举例
id :1 与另外两行相同,表示这是同一查询的一部分,按顺序执行
select_type: SIMPLE 简单查询(不包含子查询或UNION)
table: c 查询涉及 customers 表的别名
partitions: NULL 表未分区
type ref: 使用非唯一索引扫描,返回匹配 ‘USA’ 的所有行
possible_keys: PRIMARY,idx_country 可能使用主键或 country 字段的索引
key idx_country: 实际使用了 country 字段的索引
key_len: 103 索引使用的字节数(country字段为varchar(100),utf8mb4字符集)
ref: const 使用常量值 ‘USA’ 进行索引查找
rows: 50 预计需要扫描50行来找到所有美国的客户
filtered: 100.00 100%的行满足后续的过滤条件
Extra: Using index 使用了覆盖索引,无需回表查询
explain命令(8.0以上)
EXPLAIN ANALYZE SELECT * FROM your_table WHERE column_name = 'value';
-> Index lookup on your_table using index_name (column_name='value') (cost=0.35 rows=1) (actual time=0.047..0.049 rows=1 loops=1)
```
这个输出非常直观地告诉你:
Index lookup: 使用了索引查找。
using index_name: 使用的索引名称。
(actual time=...): 实际的执行时间。
1274

被折叠的 条评论
为什么被折叠?



