type列
指查询方式,是分析“查询数据过程”的重要依据
执行效率 system > const > eq_ref > ref > range > index > ALL
名称 | 含义 |
---|
system | 系统表,少量数据,往往不需要进行磁盘IO |
const | 常量连接 |
eq_ref | 主键索引(primary key)或者非空唯一索引(unique not null)等值扫描 |
ref | 非主键非唯一索引等值扫描 |
range | 范围扫描 |
index | 索引树扫描 |
ALL | 全表扫描(full table scan) |
All
全表数据扫描
意味着从表的第一行,往后逐行做全表扫描.可能扫描到最后一行
mysql> explain select * from gold_log \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: gold_log
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 63118
Extra: NULL
index
全索引扫描
通俗来说,all扫描所有数据行data_all,而index扫描所有索引节点,相当于index_all
mysql> explain select id from gold_log order by id \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: gold_log
type: index
possible_keys: NULL
key: PRIMARY
key_len: 4
ref: NULL
rows: 63118
Extra: Using index
range
索引范围扫描
mysql> explain select * from gold_log where id>5 \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: gold_log
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 31559
Extra: Using where
ref
通过索引列,直接引用到某些数据行
mysql> explain select * from gold_log where num=5 \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: gold_log
type: ref
possible_keys: num,num2
key: num
key_len: 5
ref: const
rows: 1
Extra: NULL
eq_ref
通过索引列,直接引用某一行数据
mysql> explain select a.id,b.room_id from gold_log a inner join gold_room_log b on a.id=b.log_id where a.id >0 \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: a
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 31559
Extra: Using where; Using index
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: b
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: test.a.id
rows: 1
Extra: NULL
const,system,null
这三个分别值,查询优化到了常量级别,甚至不需要查询时间
一般按照主键查询时,易出现const,system
或者直接查找某个表达式不经过表时,出现null
mysql> explain select * from t1 where id =1;
+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+
| 1 | SIMPLE | t1 | const | PRIMARY | PRIMARY | 4 | const | 1 | NULL |
+
mysql> explain select * from (select * from t1 where id=1) a;
+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+
| 1 | PRIMARY | <derived2> | system | NULL | NULL | NULL | NULL | 1 | NULL |
| 2 | DERIVED | t1 | const | PRIMARY | PRIMARY | 4 | const | 1 | NULL |
+
mysql> explain select * from t1 where id =3;
+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+
| 1 | SIMPLE | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Impossible WHERE noticed after reading const tables |
+