简单做个测试,验证并强化记忆。
结果:
只有查询(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
没有使用索引
一个查询可以只使用索引中的一部分,但只能是最左侧部分
都使用了索引