mysql 之前有讲述过关于索引的分类以及应用mysql索引应用本篇则主要是针对联合索引abc来进行实践操作说明。
大家想找employees数据包可以查看如上链接博客。
一、数据背景
创建一个联合索引abc
索引的type以及length如下:
二、key-len列的计算规则
三、SQL执行测试
1)sql执行 a,b,c字段都存在
1>abc执行
explain select * from employees where
uid
=4 andfirst_name
=“Cristinel” andlast_name
=“Haddadi”
type为ref,证明走索引了,key_len=42,我们可以计算一下。uid的type为bigint,所以就是8个字节。first_name和last_name均为varchar类型那么就是n+2,也就是14+2+16+2=34+8=42.
explain select * from employees where
first_name
=“Cristinel” anduid
=“4” andlast_name
=“Haddadi”
explain select * from employees where
uid
=“4” andlast_name
=“Haddadi” andfirst_name
=“Cristinel”
key_len都是42,所以都走了全索引
2)sql执行 a,b,c部分索引字段为查询条件
1>ac执行
explain select * from employees where
uid
=“4” andlast_name
=“Haddadi”
我们发现key_len=8,也就是只使用了uid索引,last_name索引未生效。
2> ba执行
explain select * from employees where
first_name
=“Cristinel” anduid
=“4”
我们通过计算key_len计算可以发现,14+2+8=24,他走了两个索引,ab都使用到了。
3)针对条件,优化索引
曾经遇到这样一个问题,需要满足两个查询语句
select * from A where a=a and b=b and c=c;
select * from A where a=a and c=c;
该如何建立索引呢?
那如果继续a,b,c肯定不满足语句2全部走索引。所以我们改变一下,改为a,c,b索引则均可以满足以上的两个需求。
如上图,我重新设置了一个索引a,c,b模式,通过如上的测试我们可以判定肯定满足如上的语句了。
1>a,b,c执行
explain select * from employees where
uid
=“4” andfirst_name
=“Cristinel” andlast_name
=“Haddadi”
2>a,c执行
explain select * from employees where
uid
=4 andlast_name
=“Haddadi”
key_len:16+2+8=26,索引都用到了。
四、总结
最左前缀原则,通过以上我们可以总结出,只要联和索引的字段都参与了查询,那么不管前后顺序,都是可以直接走索引的。
若表中索引过多,会影响INSERT及UPDATE性能,简单说就是会影响数据写入性能。因为更新数据的同时,也要同时更新索引。
所以能一个索引完成工作,肯定不建议建立两个。