Mysql组合索引最左前缀原则

简单做个测试,验证并强化记忆。

规则

  • MySQL查询时只使用一个索引
  • 一个查询可以只使用索引中的一部分,但只能是最左侧部分
  • 建了一个(a,b,c)的复合索引,那么相当于建了(a),(a,b),(a,b,c)三个索引

结果:

只有查询(b)、(c)、(b,c)、(c,b)没有使用索引

并不是网上说的(b,a)会使索引失效,mysql优化器会发现执行SQL查询的最佳方案。


按字段顺序查询

explain select * from abc where a = 1 ;

type: ref
key: a_b_c
ref: const

explain select * from abc where b = 1 ;

type: all

explain select * from abc where c = 1 ;

type: all

explain select * from abc where a = 1 and b = 1 ;

type: ref
key: a_b_c
ref: const,const

explain select * from abc where b = 1 and c = 1;
type: all

explain select * from abc where a = 1 and c = 1;

type: ref
key: a_b_c
ref: const

explain select * from abc where a = 1 and b = 1 and c = 1;

type: ref
key: a_b_c
ref: const,const,const


按字段乱序查询

explain select * from abc where b = 1 and a = 1 ;

type: ref
key: a_b_c
ref: const,const

explain select * from abc where c = 1 and b = 1;

type: all

explain select * from abc where c = 1 and a = 1;

type: ref
key: a_b_c
ref: const

explain select * from abc where a = 1 and c = 1 and b = 1;

explain select * from abc where c = 1 and a = 1 and b = 1;

explain select * from abc where c = 1 and b = 1 and a = 1;

explain select * from abc where b = 1 and a = 1 and c = 1;

explain select * from abc where b = 1 and c = 1 and a = 1;

均为

type: ref
key: a_b_c
ref: const,const,const


总结分析


单个查询

a
使用索引
b
c
没有使用索引

一个查询可以只使用索引中的一部分,但只能是最左侧部分


部分查询

ab
ac
ba
ca
使用索引

bc
cb
没有使用索引

一个查询可以只使用索引中的一部分,但只能是最左侧部分


全查询

都使用了索引


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值