根据我对多列索引的了解,它们仅在您使用从左侧开始的列且不跳过任何列时才有用。比如,当你有一个 (a, b, c)
的索引时,你可以查询 a
、a、b
或 a、b、c
。
但是今天我发现当有一个索引(InnoDB 表上的BTREE
)时:
some_varchar, some_bigint, other_varchar
我可以查询:
SELECT MAX(some_bigint) FROM the_table
它的计划说:
id: 1
select_type: SIMPLE
table: the_table
type: index
possible_keys: NULL
key: index_some_varchar_some_bigint_other_varchar
key_len: 175
ref: NULL
rows: 1
Extra: Using index
这似乎不同意the docs .这也令人困惑,因为 key
已设置,但 possible_keys
未设置。
这在实践中如何运作?如果键首先按 some_varchar
排序,(或它的前缀)MySQL 如何从中获取第二列的 MAX
?
(猜测是 MySQL 会收集一些关于索引中所有列的额外信息,但如果这是真的 - 是否可以直接看到它?)
最佳答案
我对索引的理解是正确的,但是对Using index
的理解是错误的。
使用索引
并不一定意味着该值是通过快速查找访问的。它只是意味着未访问行数据。当type
为index
且Extra
为Using index
时,仍然表示扫描整个索引:
来自 the documentation :
The index join type is the same as ALL, except that the index tree is scanned.
对于实际上使用索引前缀的 MAX
查找,解释如下所示:
id: 1
select_type: SIMPLE
table: NULL
type: NULL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: NULL
Extra: Select tables optimized away
关于mysql - 为什么 MAX 在索引中间的列上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068952/