MariaDB [hellodb]> explain select * from students where gender='m'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 25
Extra: Using where
id:SELECT语句的标识符(主查询的id通常为1)
select_type:查询类型
SIMPLE #简单查询
PRIMARY #union的第一个查询(或最外的查询)
UNION #在联合查询中,相对于PRIMARY的其他查询语句
UNION RESULT #UNION的执行结果
SUBQUERY #子查询
DERIVED #用于FROM子句中的子查询;
table:查询语句所关系到的表的名字;
possible_keys:表示查询时可能使用的索引
key:表示实际使用的索引
key_len:使用到索引字段的长度
rows:扫描的行数
Extra:额外信息,执行情况的说明和描述
1)using where #用where后面的语句筛选出匹配的行
2)using index #所需要的数据从索引就能够全部获取到(覆盖索引特性)
3)using index for group-by #类似using index,用于group by中
4)using filesort #将检索到的数据放到内存中进行排序,若内存装不下会放到磁盘上,性能很差
5)using index condition #过滤操作下推到存储引擎来完成
type:访问类型
1)system #表中仅有一行数据
2)const #表中至多有一行匹配且根据PRIMARY KEY或UNIQUE KEY(NOT NULL)进行查询。
如下,其中stuid为主键
1
2
3
4
5
6
7
8
9
10
11
12
13
MariaDB [hellodb]> explain select * from students where stuid=3\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: const
rows: 1
Extra:
1 row in set (0.00 sec)
MariaDB [hellodb]> explain select * from students where stuid>20\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 5
Extra: Using where
1 row in set (0.00 sec)
10)index #全索引扫描
1
2
3
4
5
6
7
8
9
10
11
12
13
MariaDB [hellodb]> explain select stuid from students\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: index
possible_keys: NULL
key: age_index
key_len: 1
ref: NULL
rows: 25
Extra: Using index
1 row in set (0.00 sec)
11)ALL #全表扫描
type由上至下性能逐渐变差。
能够使用索引场景
1)全值匹配,对索引中的列指定具体值
2)对索引列的值进行范围查询
例如:explain select * from customer where customer_id>10 and customer_id<20\G
3)最左前缀匹配
例如:select * from students where name like 'Xu%'
当使用的索引是复合索引时,where后面的条件必须包括复合索引的第一列,才能使用索引。若没有包括复合索引的第一列,而是仅适用于后面的几列,则不会利用索引。
4)只访问索引的查询,查询的列都在索引的字段中,效率较高
MariaDB [hellodb]> explain select * from students where name=1\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: ALL
possible_keys: name_index
key: NULL
key_len: NULL
ref: NULL
rows: 25
Extra: Using where
1 row in set (0.00 sec)
若把name后面的字符串加上引号则可以使用索引
1
2
3
4
5
6
7
8
9
10
11
12
13
MariaDB [hellodb]> explain select * from students where name='1'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: students
type: ref
possible_keys: name_index
key: name_index
key_len: 152
ref: const
rows: 1
Extra: Using index condition
1 row in set (0.00 sec)