MySQL explain指令中type为index的第二个场景是什么?
想要问一下第二种情况发生的具体场景。
最后想问一下“MySQL can use this join type when the query uses only columns that are part of a single index.”这句话。我现在有以下场景:
create table t1(
f1 int not null,
f2 int not null,
f3 int not null,
primary key(f1),
index f(f2, f3));
mysql> explain select * from t1; | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
1 | SIMPLE | t1 | NULL | index | NULL | f | 8 | NULL | 4 | 100.00 | Using index |
1 row in set, 1 warning (0.00 sec)
简单来说,第二种情况是当MySQL可以只通过扫描索引就能完成查询时发生的。这种情况通常称为"覆盖索引"(covering index)。
关于你给的例子:
结果显示type是"index"且Extra是"Using index",这确实有点特别。正常情况下,SELECT * 需要获取所有列,不应该能只用索引完成查询。
可能的结果就是:
那句话"MySQL can use this join type when the query uses only columns that are part of a single index"的意思是:当你的查询只需要获取某个索引包含的列时,MySQL可以完全从索引中获取数据,不需要回表。
比如如果你查询
SELECT f2, f3 FROM t1
,MySQL可以直接从索引f(f2, f3)中获取所有数据,不需要访问数据表本身。说实话,你这个例子挺特殊的,可能需要进一步测试才能完全理解MySQL在这种情况下的行为。