联合索引的左匹配原则

联合索引:

key : ‘index_name_age’(‘name’,‘age’)

场景:

case1:

 select  * from person_info where name='gxf' and age = '18';

此时会走 index_name_age 联合索引。

case2:

select  * from person_info where name='gxf' ;

此时会走 index_name_age 联合索引。

case3:

select  * from person_info where age = '18';

此时不会走 index_name_age 联合索引。会全表扫描。

注意

1.最左前缀 匹配原则

mysql会一直向右匹配 直到遇到 > 、< 、 between 、like 就停止匹配。

where a=1 and b=2 and c=3 and d>4;

如果建立 index(a,b,d,c) 则c是用不到索引的。
如果建立 index(a,b,c,d) 则都可用到索引。
如果建立 index(b,c,a,d) 则都可用到索引。

2.= 和 in

可以乱序

如果建立 index(a,b,c,d)。

where a=1 and b=2 and c=3 and d in(4,5);
where a=1 and d in(4,5) and b=2 and c=3 ;

都可走索引,因为mysql会优化你的SQL把顺序调整成可以使用索引的形式。

为什么case3不走联合索引:

在这里插入图片描述

假设:现在有个联合索引 index(col3,col2);
则,联合索引文件里就会存储一个B+树,叶子节点会存储两个Alice的行数据,并且会在此基础上,再根据col2排序。最终结果:34的Alice排在了77的Alice的前面。

现在 where col3 = ‘Alice’ and col2=34; 则会先找到叶子节点,再去找34。即走了索引。

若 where col2 = 34;则这个联合索引文件存的B+树就用不了了。即不能走索引。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值