You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何MySQL可对两个单列索引使用索引条件查询?

MySQL同时使用两个单列索引的原理解析

先贴出你的表结构和查询语句,方便上下文参考:

表创建语句

create table student (
id integer not null auto_increment,
name varchar(20) not null default '',
age integer not null default 0,
create_time datetime not null default '1970-01-01 00:00:00',
primary key (id) using btree,
key idx_student_name(name) using btree,
key idx_student_age(age) using btree
)

查询语句

explain select * from student s where name like 'ron%' and age > 10

你看到的EXPLAIN结果显示用到两个单列索引,是因为MySQL启用了索引合并(Index Merge)优化策略中的交集合并(Intersection Merge),具体逻辑如下:

  • name like 'ron%'是前缀匹配模式,完全可以利用idx_student_name索引快速定位到所有符合条件的记录主键ID;age > 10是范围条件,同样能通过idx_student_age索引获取对应记录的主键ID。
  • MySQL优化器经过成本计算后认为:单独使用某一个索引时,后续需要过滤大量不符合另一个条件的数据,效率不如同时使用两个索引分别获取主键集合,再取两个集合的交集,最后通过主键ID回表查询完整数据。
  • 触发该优化的核心条件:两个查询条件各自都能匹配对应的单列索引,条件之间是AND(交集)关系,且优化器判定这种合并方式的执行成本低于单索引扫描或全表扫描。

补充说明:如果name的查询条件是%ron(后缀匹配),由于无法利用idx_student_name索引,就不会触发索引合并,只会选择idx_student_age索引或直接全表扫描。

内容的提问来源于stack exchange,提问作者byron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:40:37