什么是最左前缀法则呢?最左前缀法则是指复合索引当中要遵守的法则,先说结论:指查询从索引的最左列开始,并且不跳过索引中的列。也就是说查询的条件当中要包含索引最左侧的列,并且不能跳过索引当中的列。
如何理解呢?实际来个例子吧
create index idx_seller_name_sta_addr on tb_seller(name, status, address);
explain select * from tb_seller where name = '小米科技' and status = '1' and address ='北京市' //针对上面的索引,这样来查肯定是没有问题的
接下来再做一个测试 :
explain select * from tb_seller where name = '小米科技' //这样会走索引吗?结论是:也会
接下来进一步做测试:
explain select * from tb_seller where name = '小米科技' and status = '1' //结论:也会走索引,可以看key_len区分索引的不同
接下来再做一下测试:
explain select * from tb_seller where status = '1' and address = '北京市' //这样走索引吗?不走,因为没从索引最左边的列开始
再做一轮测试:
explain select * from tb_seller where address = '北京市' //这样走索引吗?不走,因为也没从索引最左边的列开始
再做一轮测试:name顺序发生变化
explain select * from tb_seller where status = '1' and address = '北京市' and name = '小米科技' //走索引,顺序并不影响,只看查询条件有没有包含最左列
还有一种特殊情况:
explain select * from tb_seller where name = '小米科技' and address = '北京市' //走索引,只用到了name字段的索引,没用到address字段的索引
可以把这个想象成爬楼梯,name 第一层,status 第二层,address 第三层,不能跳过第一层,直接爬后面的。也不能爬完第一层后直接爬第三层。