单列索引:即一个索引只包含单个列。
联合索引:即一个索引包含了多个列。
mysql> explain select id,name,phone from tb_user where phone = '17799990015' and name ='妲己'\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: tb_user
partitions: NULL
type: const
possible_keys: idx_user_phone
key: idx_user_phone
key_len: 35
ref: const
rows: 1
filtered: 100.00
Extra: NULL
1 row in set, 1 warning (0.00 sec)
对于上面的sql语句,MySQL选择了idx_user_phone
这个单列索引,有用还需要查询name
字段,所以会回表查询
如果我们再来创建一个phone和name字段的联合索引
create unique index idx_user_phone_name on tb_user(phone,name);
我们指定这个索引查询结果
mysql> explain select id,name,phone from tb_user use index (idx_user_phone_name) where phone = '17799990015' and name ='妲己'\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: tb_user
partitions: NULL
type: const
possible_keys: idx_user_phone_name
key: idx_user_phone_name
key_len: 187
ref: const,const
rows: 1
filtered: 100.00
Extra: Using index
1 row in set, 1 warning (0.00 sec)
Using index
表面我们没有回表操作。
总结:在业务场景中,如果存在多个查询条件,考虑针对于查询字段建立索引时,建议建立联合索引,而非单列索引。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1909773034@qq.com