防止索引失效

索引:排好序利于快速查找的数据结构(Btree)

explain/show profile
1、type
all - index - range - ref - eqref - const - system
全文扫描不走索引 - 遍历索引 - 取索引的某个范围 - 取索引字段等于某值的所有行 - 等于某值的唯一行 - ??
2、keylen 索引长度
3、rows 读取行数
4、Extra
using index 使用覆盖索引
using where 没啥用
using temporary 使用临时表,需避免,常见排序分组
using filesort 无法使用索引完后排序,而直接走文件排序

防止索引失效情况:
1、最佳左前缀,中间不可断掉;
2、索引列不要做函数、计算、类型转化等操作,譬如where name = 123
3、范围后边全失效,范围字段本身不失效
4、避免用 != > < 及 is null 、not null
5、索引列不能有null
6、like 'xx%'走索引,like '%xx%' 不走

建立复合索引 create index idx_c1_c2_c3_c4 on table t_xx(c1,c2,c3,c4);
where查询条件:
1、 c1 = 'c1'
2、 c1 = 'c1' and c2 = 'c2'
3、 c1 = 'c1' and c2 = 'c2' and c3 = 'c3'
4、 c1 = 'c1' and c2 = 'c2' and c3 = 'c3' and c4 = 'c4'
以上全都用到索引,type为ref,只不过keylen不同。若where条件中不出现c1则根本不走索引

5、 c1 = 'c1' and c3 = 'c3' and c2 = 'c2' and c4 = 'c4'
6、 c4 = 'c4' and c3 = 'c3' and c2 = 'c2' and c1 = 'c1'
查询条件都是等于某个常量或order by时,即使顺序混乱,mysql会自动优化,结论同1~4

7、 c1 = 'c1' and c2 = 'c2' and c3 > 'c3' and c4 = 'c4'
type为range,用到3个分段索引,c3段的索引也是用到的

8、 c1 = 'c1' and c2 = 'c2' and c4 > 'c4' and c3 = 'c3'
type为range,用到4个分段索引

9、 c1 = 'c1' and c2 = 'c2' and c4 = 'c4' order by c3
10、c1 = 'c1' and c2 = 'c2' order by c3
type为ref,c1、c2段查找,c3段排序,因为索引的另一个功能就是排序

11、c1 = 'c1' and c2 = 'c2' order by c4
type为ref,2分段查找。少了c3破坏了索引,排序只能using filesort

12、c1 = 'c1' and c5 = 'c5' order by c2,c3
type为ref,c1段查找。c2、c3段索引用于排序,无filesort

13、c1 = 'c1' and c5 = 'c5' order by c3,c2
c1用于查找,因为顺序反了,有filesort

14、c1 = 'c1' and c2 = 'c2' and c5 = 'c5' order by c3,c2
无filesort,因为c2已经是常量,c2就不用排序了,不存在顺序颠倒

15、c1 = 'c1' and c4 = 'c4' group by c2,c3
分组前必然排序,Extra很和谐

16、c1 = 'c1' and c4 = 'c4' group by c3,c2
Extra 产生using temporary 和 using filesort

你可能感兴趣的:(防止索引失效)