MySql学习笔记(七):explain-索引的使用状况

主要内容:explain的possible_key、key、key_len、ref、rows入门。mysql

一、possible_keysql

表示在查询过程当中可能用到的索引。查询涉及到的字段上若是有索引,则该索引会出如今possible_key列中表示可能用到,但实际上并不必定会用到。例:数据库

mysql> explain select * from t_blog where id = 1;

+----+-------------+--------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table  | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+--------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | t_blog | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
+----+-------------+--------+-------+---------------+---------+---------+-------+------+-------+
1 row in set

由于id是t_blog的主键,查询时涉及到了该字段,possible_key列中有主键字样。ide

二、key优化

表示再查询过程当中实际用到的索引,若是为null则表示没有用到索引blog

如上例,key为主键,表示查询过程当中用到了主键。完整解读:理论上要用到主键,实际上确实用到了主键。
索引

存在理论上应该用到某索引,但实际上没有用到,即索引失效;it

若是查询中使用了覆盖索引(select子句与符合索引顺序和字段彻底相同),possible_key为null,key为覆盖索引。入门

三、key_lentable

索引中使用的字节数,越短越好。这个值表示最大可能使用长度而不是实际使用长度,例如:

mysql> explain select * from t_blog where title = 'C语言精讲';
+----+-------------+--------+------+---------------+---------+---------+-------+------+--------------------------+
| id | select_type | table  | type | possible_keys | key     | key_len | ref   | rows | Extra                    |
+----+-------------+--------+------+---------------+---------+---------+-------+------+--------------------------+
|  1 | SIMPLE      | t_blog | ref  | index_1       | index_1 | 153     | const |    1 | Using where; Using index |
+----+-------------+--------+------+---------------+---------+---------+-------+------+--------------------------+
1 row in set

此时,查询条件多一个:

mysql> explain select * from t_blog where title = 'C语言精讲' and typeId = 2;
+----+-------------+--------+------+---------------+---------+---------+-------------+------+--------------------------+
| id | select_type | table  | type | possible_keys | key     | key_len | ref         | rows | Extra                    |
+----+-------------+--------+------+---------------+---------+---------+-------------+------+--------------------------+
|  1 | SIMPLE      | t_blog | ref  | index_1       | index_1 | 158     | const,const |    1 | Using where; Using index |
+----+-------------+--------+------+---------------+---------+---------+-------------+------+--------------------------+
1 row in set

查询条件变多,精度变高,同时key_len也在变大。

四、ref

显示索引的哪一列被使用了,可能的话是一个常量。

一共有两种格式:

1>const:常量,where <索引>='常量'

2><数据库名>.<表名>.<字段名> :某数据库中的某表中的某列被使用

五、rows

每张表有多少行被优化器查询

相关文章
相关标签/搜索