前文我们讲解了索引失效的原则。已经索引要遵循最左前缀法则。
原则:尽量使用覆盖索引,减少select *的使用。
那么什么是覆盖索引呢? 覆盖索引是指查询使用了索引,并且需要返回的列,在该索引中已经全部能够找到 。
接下来,我们来看一组SQL的执行计划,看看执行计划的差别,然后再来具体做一个解析。
- explain select id, profession from tb_user where profession = '软件工程' and age =
- 31 and status = '0' ;
-
- explain select id,profession,age, status from tb_user where profession = '软件工程'
- and age = 31 and status = '0' ;
-
- explain select id,profession,age, status, name from tb_user where profession = '软件工程' and age = 31 and status = '0' ;
-
- explain select * from tb_user where profession = '软件工程' and age = 31 and status
- = '0';
这些sql主要的不同在于,select查询结果的不同




我们可以看出后两个Extra是null并不是前面两个的Using Index。
| Extra | 含义 |
| Using Index | 查找使用了索引,但是需要的数据都在索引列中能找到,所以不需 要回表查询数据 |
| Null | 查找使用了索引,但是需要回表查询数据 |
因此覆盖索引,就是建立的索引包含了,要查找的全部字段

聚集索引是主键建立的,数据中包含了一行的全部内容。



因此我们写sql语句和建立索引时,应该避免回表扫描带来的影响。