小心MySQL联合索引的效率陷阱

场景:

表中有两个索引:索引index_1(create_Time, category_id), index_2(category_id) 

查询语句为:select create_time,category_id from table where create_time='15233333333' and category_id='666';

explain结果:

使用了index_2而没有使用index_1

原因:

当一个表有多条索引可走时,  Mysql  根据查询语句的成本来选择走哪条索引(选择索引所在列长度小的), 联合索引的话, 它往往按照最左原则计算最左边的一列的大小,那么create_time明显要比category_id长的的多,所以查询构造器默认选择使用index_2,无法使用联合索引,查询效率大大降低。

解决方法:

1、改变联合索引index_1中两列的顺序,第一列使用长度小的 ORCE INDEX (FIELD1) 

2、使用hint强制使用index_1:select create_time,category_id from table force index(index_1) where create_time='15233333333' and category_id='666';

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/84773067