大家都知道mysql联合索引,在使用>、<、like这些范围查询后会失效,但是使用>=和<=从执行计划上看索引没有失效。
表:
索引:
idx_name_age_email (name,age,email)
执行语句:
1、explain select * from demo where name = 'aa' and age >6 and email = 'xxx'
key
key_len
idx_name_age_email
128
通过key_len计算,使用了(name,age)索引
1、explain select * from demo where name = 'aa' and age >=6 and email = 'xxx'
key
key_len
idx_name_age_email
331
通过key_len计算,使用了(name,age,email)索引
原因:
是Mysql5.6之后优化器的逻辑。
select * from demo where name = 'aa' and age >=6 and email = 'xxx'; 可以命中 name,age,email。原因是:
这条SQL会被优化器拆分成两部分
where where name = 'aa' and age =6 and email = 'xxx'
union all
where where name = 'aa' and age >6 and email = 'xxx'
执行计划打印出来的结果中,就能看到可以命中 a,b,c 三列了。
补充:
自从MySQL 5.6版本开始加入ICP(index condition pushdown )特性后,where a=1 and b>1 and c=1 这种情况也是有可能从ICP特性受益,也能命中 a,b,c 三列,要看具体情况而定,优化器会自行判定。ICP会体现在extra里【use index condition】。
常见的extra字段:
-
Using where:表示优化器需要通过索引回表查询数据;
-
Using index:表示直接访问索引就足够获取到所需要的数据,不需要通过索引回表;
-
Using index condition:在5.6版本后加入的新特性(Index Condition Pushdown);