Mysql联合索引的列命中

我们给某表A,B,C三个字段新建联合索引,顺序为ABC

# 创建测试表
create table a_test
(
  a varchar(20) default  null,
  b varchar(20) default  null,
  c varchar(30) default  null,
  d varchar(40) default  null
);
# 创建联合索引
create index table_name_a_b_c_index
  on a_test (a, b, c);

Mysql的联合索引,根据, 有a,ab,abc三个最左索引前缀可供命中

即:只要查询条件中带有a字段条件,或者同时带有ab两个字段的条件,或者同时带有abc三个字段的条件,都会使用到联合索引abc
例1:
explain select * from a_test where  a=ss and b = c  and d=c and c=c

该sql语句的查询条件可以组成abc索引前缀,完整的使用了abc联合索引


例2:
explain select * from a_test where  a=ss and b = c  and d=c

该sql语句的查询条件可以组成ab索引前缀,使用了abc联合索引的ab部分


例3:
explain select * from a_test where a=ss and d=c

该sql语句的查询条件可以组成A索引前缀,使用了abc联合索引的 a部分


例4:
explain select * from a_test where  b = c  and d=c and c=cc

该sql语句并未使用到abc联合索引,因为 无法组成 最左索引前缀

我们给某表A,B,C三个字段新建联合索引,顺序为ABC # 创建测试表 create table a_test ( a varchar(20) default null, b varchar(20) default null, c varchar(30) default null, d varchar(40) default null ); # 创建联合索引 create index table_name_a_b_c_index on a_test (a, b, c); Mysql的联合索引,根据, 有a,ab,abc三个最左索引前缀可供命中 即:只要查询条件中带有a字段条件,或者同时带有ab两个字段的条件,或者同时带有abc三个字段的条件,都会使用到联合索引abc 例1: explain select * from a_test where a=ss and b = c and d=c and c=c 该sql语句的查询条件可以组成abc索引前缀,完整的使用了abc联合索引 例2: explain select * from a_test where a=ss and b = c and d=c 该sql语句的查询条件可以组成ab索引前缀,使用了abc联合索引的ab部分 例3: explain select * from a_test where a=ss and d=c 该sql语句的查询条件可以组成A索引前缀,使用了abc联合索引的 a部分 例4: explain select * from a_test where b = c and d=c and c=cc 该sql语句并未使用到abc联合索引,因为 无法组成 最左索引前缀
经验分享 程序员 微信小程序 职场和发展