-- 结果值从最好到最坏依次是:system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL。SQL 性能优化的目标:至少要达到 range 级别,要求是 ref 级别,最好是 consts级别。(阿里巴巴开发手册要求)-- 1.等值匹配-- 1.1.`system`。当表中只有一条记录并且该表使用的在储引擎的统计数据是精确的,比如MyISAM、Memoryexplainselect*from demo where id ='1';-- 1.2.`const`。当我们根据主键或者唯一索引列与常数进行等值匹配时,对单表的访问方法就是`const`explainselect*from demo where id2 ='1';-- 1.3.`eq_ref`。在连接查询时,如果被驱动表是通过主键或者唯一二级索引列等值匹配的方式进行访问的(如果该主键或者唯一二级索引是联合索引的话,所有的索引列都必须进行等值比较),则对该被驱动表的访问方法就是`eq ref`explainselect*from demo a,demo b where a.id2 = b.id2;-- 1.4.`ref`。当通过普通的二级索引列与常量进行等值匹配时来查询某个表,那么对该表的访问方法就可能是`ref`explainselect*from demo where id3 ='1';explainselect*from demo where id2 isnull;-- 对比上面的1.2.explainselect*from demo a,demo b where a.id3 = b.id3;-- 对比上面的1.3.-- 2.模糊、范围查询等-- 2.1.`fulltext`略-- 2.2.`ref_or_null`。当对普通二级索引进行等值匹配查询,该索引列的值也可以是`NULL`值时,那么对该表的访问方法就可能是`ref_or_null`explainselect*from demo where id2 ='1'or id2 isnull;-- 如果字段有not null约束,则为const(唯一索引时)、ref(普通索引时)explainselect*from demo where id3 ='1'or id3 isnull;-- 如果字段有not null约束,则为const(唯一索引时)、ref(普通索引时)-- 2.3.`index_merge`。单表访问方法时在某些场景下可以使用`Intersection`、`Union`、`sort-Union`这三种索引合并的方式来执行查询explainselect*from demo where id2 ='1'or id3 ='2';explainselect*from demo where id2 ='1'or id3 in('2','3');-- 2.4.`unique_subquery`。是针对在一些包含`IN`子查询的查询语句中,如果查询优化器决定将`IN`子查询转换为`EXISTS`子查询,而且子查询可以使用到唯一索引进行等值匹配的话。explainselect*from demo a where id4 in(select id2 from demo where id4 = a.id4)or id4 ='1';-- 2.5.`index_subquery`。是针对在一些包含`IN`子查询的查询语句中,如果查询优化器决定将`IN`子查询转换为`EXISTS`子查询,而且子查询可以使用到普通索引进行等值匹配的话。explainselect*from demo a where id4 in(select id3 from demo where id4 = a.id4)or id4 ='1';-- 2.6.`range`。如果使用索引获取某些`范围区间`的记录,那么就可能使用到`range '访问方法explainselect*from demo where id in('1','2');explainselect*from demo where id >'1';explainselect*from demo where id between'1'and'2';explainselect*from demo where id like'1%';-- 注意:id为数字类型,索引失效-- 3.全表扫描-- 3.1.`index`。当我们可以使用索引覆盖,但需要扫描全部的索引记录时,该表的访问方法就是`index`explainselectdistinct id3 from demo;-- 如果id3有大量重复数据时,则为rangeexplainselect id from demo;-- 3.2.`ALL`各种未使用索引(索引失效情况)的情况explainselectdistinct id4 from demo;explainselect id4 from demo;explainselect*from demo where id isnotnull;