我在事务表上创建了一个 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
列下的查询 MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain
上运行 EXPLAIN 时,我得到 by_reference_parent_ref_kind
并且在 Extra
列下我有 Using index condition
这似乎暗示索引实际上已被使用。
这怎么可能?
最佳答案
它将使用索引,因为您在查询(引用
)中列出了最左边的列,即文档中的用例(col1)。条件 (kind
) 中的另一列不会通过索引进行搜索。
关于Mysql 解释显示查询正在使用索引,而根据 Mysql 文档,它不应该使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56392624/