# 创建索引 xxx是表名 a,b,c是创建索引的字段名
alter table xxx add INDEX `sindex` (`a`,`b`,`c`);
# 情况一 使用单条件查询时,索引使用情况如下 (只会用到 a 的索引)
# type=ref,key=sindex,key_len=163,ref=const
select * from xxx where a = '1';
# 没有使用到索引 type=all
select * from xxx where b = '1';
# 没有使用到索引 type=all
select * from xxx where c = '1';
## 情况二 使用索引的两个条件
# type=ref,key=sindex,key_len=966,ref=const,const
select * from xxx where a = '1' and b = '1';
# type=ref,key=sindex,key_len=966,ref=const,const
select * from xxx where b = '1' and a = '1';
# 上面互换位置后,索引使用情况一致,说明sql顺序不会影响索引。感觉应该是mysql在执行查询前,会自动优化。
# type=ref,key=sindex,key_len=163,ref=const 只会用到a索引
select * from xxx where a = '1' and c = '1';
# 没有使用到索引 type=all
select * from xxx where b = '1' and c = '1';
### 情况三 使用索引的三个条件
# type=ref,key=sindex,key_len=1129,ref=const,const,const 使用到3个索引
select * from xxx where a = '1' and b = '1' and c = '1';
总结:
创建a,b,c联合索引就相当于创建了 (a),(a,b),(a,b,c) 3个索引。
有问题请下方留言,感谢!