之前只知道索引会让查询效率变快,各种博文也只是介绍触发联合索引的条件是在where条件里使用联合索引的全部索引键,可触发索引的使用。 但都没有提到在联合索引里设置的字段顺序会大大影响查询效率!!
拿一个简单的查询语句举例,我们想获取表a里特定城市(e.g.深圳)一年的某个指标值:
select month_code, dept_code, city_name, index_code, index_name, index_level, index_value
from table_a where month_code>= 202001 and month_code <= 202006
and city_name = 'shenzhen' and index_code = 'CA001' and index_level = 3
如果不设置索引直接查询,大概要大概2秒左右。表table_a一个月10万数据量左右,一年就120w。
所以加了个联合索引,
alter table table_a add index index_p1(month_code,city_name,index_code,index_level)
加了之后查询效率还是在1.3秒左右,并没有快多少。我的索引都是where条件里的,是都命中了的,但索引提升的查询效率不应该只提高这么点的…这说明索引没有发挥很大的作用。还需要注意的是mysql中where条件里的字段顺序并不影响命中索引,它能够自动优化成索引识别的形式。
经过研究发现根本原因在于设置索引里的字段顺序,这个是个决定性因素。如果把索引设置为:
alter table table_a add index index_p2(city_name,month_code,ind