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
没有使用索引

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


全查询

都使用了索引


你可能感兴趣的:(数据库)