MySQL 索引失效
为了测试索引失效,首先创建一个用于测试的数据表
1 | create table |
索引失效的几种常见场景
- select语句中有is null或者is not null查询判断。索引是一棵B+树,节点中不会存储NULL值。
1 | MariaDB [test]> explain select * from student where age is null \G; |
- 前导模糊查询不能利用索引,例如查询字段使用
like '%XX'
或者like '%XX%'
1 | MariaDB [test]> explain select * from student where name like '%a' \G; |
- 查询条件有or
1 | MariaDB [test]> explain select * from student where name='a' or name='b' \G; |
- 不符合左前缀法则的查询,跳过多列索引的第一列
1 | MariaDB [test]> explain select * from student where age=10 \G; |
- 范围查询
> < between
1 | MariaDB [test]> explain select * from student where name>='a' \G; |
- 查询条件使用函数在索引列上,或者对索引列进行运算
1 | MariaDB [test]> explain select * from student where left(name, 1)='a' \G; |
- not in/not exists
1 | MariaDB [test]> explain select * from student where name not in ('c', 'b') \G; |
- 隐式转换导致索引失效,
name
是一个字符串字段,select
查询时传入数字,mysql会把数字转换为字符串,然后做全表扫描
1 | MariaDB [test]> explain select * from student where name = 11 \G; |