索引失效原则

1. 复合索引跨列无序使用
2. 复合索引中使用!=、<、>、NOT NULL、IS NOT NULL等会导致自身以及右侧索引失效
3. 对索引列进行操作包括但不限于函数、计算、类型转换
4. LIKE关键字进行模糊匹配查询中模糊匹配符号居左会导致自身以及右侧索引失效
5. 进行避免使用IN关键字(查询内容超过总内容30%转为全表查询会导致索引失效),OR关键字(会导致右侧索引失效)

索引失效的例子

复合索引(a,b,c)

1. where a=3 and b=5 and c=4;  【a,b,c 走索引】

2. where c=4 and b=6 and a=3; 【c,b,a 底层自动优化 走索引】

3. where a=3 and c=7; 【a走索引,c跨列使用不走索引】

4. where a=3 and b>7 and c=3; 【a,b走索引,b索引是范围值但阻塞了c,c不走索引】

5. where b=3 and c=4; 【b、c跨列使用,不走索引】

6. where a>4 and b=7 and c=9; 【a走范围索引,阻塞了b、c,b、c不走索引】

7. where a=3 order by b; 【a、b走索引】

8. where a=3 order by c; 【a走索引,c跨列使用不走索引】

9. where b=3 order by a; 【b跨列使用导致b、a都不走索引】

单列索引(age)

where age = 20; 【走索引】
where age+10 = 30; 【不走索引】
where age = 30-10; 【走索引】

where concat('sname','age') = 'test'; 【不走索引】
where age = concat('sname','test'); 【走索引】

单列索引(name)

where name like '前缀%' 【走索引】
where name like '%后缀' 【不走索引,扫描全表】

字符串列与数字比较 ★ 【字符串 = 数字】不走索引

INDEX('a' char(10))
where a = '1'; 【走索引】
where a = 1; 【不走索引】

INDEX('b' int)
where b = '1'; 【走索引】
where b = 1; 【不走索引】
学而不思则罔,思而不学则殆!