访问类型排序:
System:表只有一行记录(等于系统表),这是const类型的特列,平时不会出现,这个也可以忽略不计。
Const:表示通过索引一次就找到了,const用于比较primary key或者unique索引。因为只匹配一行数据,所以很快,如将主键置于where列表中,MySQL就能将该查询转换为一个常量。
eq_ref:唯一性索引扫描,对于每个索引键,表中只有一条记录与之匹配。常见于主键或唯一索引扫描。
Ref:非唯一性索引扫描,返回匹配某个单独值的所有行。本质上也是一种索引访问,它返回所有匹配某个单独值的行,然而,它可能会找到多个符合条件的行,所以他应该属于查找和扫描的混合体。
Range:只检索给定范围的行,使用一个索引来选择行。key 列显示使用了哪个索引
一般就是在你的where语句中出现了between、<、>、in等的查询这种范围扫描索引扫描比全表扫描要好,因为它只需要开始于索引的某一点,而结束语另一点,不用扫描全部索引。
Index:Full Index Scan,index与ALL区别为index类型只遍历索引树。这通常比ALL快,因为索引文件通常比数据文件小。也就是说虽然all和Index都是读全表,但index是从索引中读取的,而all是从硬盘中读的。
All:Full Table Scan,将遍历全表以找到匹配的行。
从最好到最差依次是:system>const>eq_ref>ref>range>index>All 。一般来说,最好保证查询能达到range级别,最好能达到ref。
-- tpye
#All
explain select * from t1 where t1.content = "abc";
#system
explain select * from (select t1.id from t1 where id = 1) t;
#const 索引一次就找到了
explain select * from t1 where id = 1;
#eq_ref
explain select t1.*,t2.*
from t1
join t2
on t1.id = t2.id;
#ref非唯一索引扫描
alter table t1 add index idx_t1_content(content);
explain select * from t1 where t1.content = "abc";
#range
explain select * from t2 where t2.id >0;
#index
explain select id,content from t1;