1.覆盖索引

覆盖索引:查询列就是索引列,索引列包含了查询列。
尽量使用覆盖索引,避免使用select *。

2.or 索引失效的情况

用or分割开的条件,如果or前的条件中的列有索引,而后面的列中没有索引,那么涉及的索引都不会被用到。
示例,name字段是索引,而createtime不是索引列,中间是or进行连接是不走索引的:
explain select * from where name = ‘szw’ or createtime = ‘2020-01-01’\G;

3.以%开头的like模糊查询,索引失效

如果仅是尾部模糊匹配,索引不会失效,如图是头部模糊匹配,索引失效。

解决方案:使用覆盖索引,则头部模糊匹配,索引不会失效

4.全表扫描更快

如果mysql评估使用索引比全表扫描更慢,则不使用索引。

5.is null、is not null,有时索引失效

如果表中null值占大多数,则is null不走索引,走全表扫描会更快,is not null 走索引;
如果表中null值占少数,则is null走索引,is not null 不走索引,走全表扫描更快。

6.in 走索引,not in 索引失效

7.单例索引和复合索引

尽量使用复合索引,少使用单例索引。
创建复合索引:
create index item_index on tb(name,status,address);
相当于创建了三个索引:
name;
name+status;
name+status+address。

创建多个单列索引,执行查询时,MySQL会选择最优(辨识度高的索引列,查询条件在索引列中占比最少的那个,将作为使用的索引)的一个作为索引。
create index item_index on tb(name);
create index item_index on tb(status);
create index item_index on tb(address);

8.查看索引使用情况

show status like ‘Handler_read%’; 查看当前会话使用索引

show global status like ‘Handler_read%’;查看全局使用索引,即从此次MySQL开机开始算起。
mysql学习-索引

相关文章: