Mysql Explain 显示查询正在使用索引,而根据 Mysql 文档,它不应该使用
Mysql Explain shows that query is using index when it shouldnt be according to Mysql doc
我在事务 table 上创建了一个 mysql 多列索引。该索引使用 3 列,如我的 rails 架构中所述:
add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree
现在我有这个活动记录查询:
MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")
纯 sql 给出:
"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"
现在从我读到的关于 mysql 和多列索引的内容来看:
If the table has a multiple-column index, any leftmost prefix of the
index can be used by the optimizer to look up rows. For example, if
you have a three-column index on (col1, col2, col3), you have indexed
search capabilities on (col1), (col1, col2), and (col1, col2, col3).
For more information, see Section 8.3.5, “Multiple-Column
Indexes”.
对我来说,这意味着前面的查询不应该使用以前的索引。
然而,当我在 key
列下 运行 EXPLAIN 我的查询 MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain
时,我得到 by_reference_parent_ref_kind
并且在 Extra
列下我有 Using index condition
这似乎暗示实际使用了索引。
这怎么可能?
它将使用索引,因为您在查询 (reference
) 中列出了最左边的列,即文档中的用例 (col1)。条件(kind
)中的另一列未通过索引搜索。
给出
WHERE reference = '...' AND kind = '...'
和
INDEX(reference, parent, kind)
优化器可以使用索引,但只能使用 reference
部分。
另一方面,如果查询中提到的唯一列是这三个,则该索引是 "covering",因此优化器有另一个使用该索引的原因。
请提供EXPLAIN SELECT ...
。在 Key_len
列中,它会提示仅使用 reference
。在Extra
栏中,Using index
是线索,它是"covering"。
这对当前查询来说是一个更好的索引,但对其他查询来说可能更差:
INDEX(reference, kind, parent)
我在事务 table 上创建了一个 mysql 多列索引。该索引使用 3 列,如我的 rails 架构中所述:
add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree
现在我有这个活动记录查询:
MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")
纯 sql 给出:
"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"
现在从我读到的关于 mysql 和多列索引的内容来看:
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3). For more information, see Section 8.3.5, “Multiple-Column Indexes”.
对我来说,这意味着前面的查询不应该使用以前的索引。
然而,当我在 key
列下 运行 EXPLAIN 我的查询 MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain
时,我得到 by_reference_parent_ref_kind
并且在 Extra
列下我有 Using index condition
这似乎暗示实际使用了索引。
这怎么可能?
它将使用索引,因为您在查询 (reference
) 中列出了最左边的列,即文档中的用例 (col1)。条件(kind
)中的另一列未通过索引搜索。
给出
WHERE reference = '...' AND kind = '...'
和
INDEX(reference, parent, kind)
优化器可以使用索引,但只能使用 reference
部分。
另一方面,如果查询中提到的唯一列是这三个,则该索引是 "covering",因此优化器有另一个使用该索引的原因。
请提供EXPLAIN SELECT ...
。在 Key_len
列中,它会提示仅使用 reference
。在Extra
栏中,Using index
是线索,它是"covering"。
这对当前查询来说是一个更好的索引,但对其他查询来说可能更差:
INDEX(reference, kind, parent)