几个常见的单表访问方法。总结自小青蛙的小册。
1、const
- 主键等值查询
- 唯一二级索引等值查询(NULL值除外)
2、ref
- 普通二级索引等值查询
- 二级索引NULL值查询
- 多个列的二级索引时,需要最左边的依次满足等值查询才可以。 比如有二级索引 (a,b,c)
select * from table where a = 1 and b = 2; ref
select * from table where a = 1; ref
select * from table where b = 2; not ref
select * from table where a = 1 and b > 2; not ref
3、ref_or_null
当使用二级索引等值查询某个值的时候,还想顺带着查出该字段为NULL值的情况。
4、range
列a上建有二级索引
select * from table where a in (1, 100) or (a > 150 and a < 200)
如上面这个查询其实就是四个区间范围
- a = 1
- a= 100
- 150 < a < 200
聚簇索引和非聚簇索引都可以。
5、index
如下联合索引(a,b,c)
select a,b,c from table where b = 100;
此时要查的列可以直接从二级索引中全部找到,并且条件也是二级索引中的列,所以可以直接在二级索引中判断条件是否满足,而无需再次回表找相关数据。此时就是index 方式。
##EXPLAIN 列 extra 列参数解释
记录几个比较常见的 extra列的值。
- Using index
查询的列和条件列都是某个二级索引里的列的时候。 - Using index condition
使用了索引下推优化之后。(5.6版本才有此特效) - Using where
全表扫描时并且使用了where的条件。
使用索引列查询某条件 并且条件中还有非索引列时。 - Using filesort
- Using temporary