Mysql 解释显示查询正在使用索引,而根据 Mysql 文档,它不应该使用索引

标签 mysql indexing explain

我在事务表上创建了一个 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/

相关文章:

php - 用户信息未进入MYSQL数据库

indexing - 了解 Marklogic 中的范围索引

mysql - 几乎相同的查询给出不同的执行时间

elasticsearch - 了解elasticsearch查询说明

mysql - 为什么这个 MySQL 查询解释计划只有三行?

php - 如何在 session 中显示用户 ID?

python - 启用 Python 通过 SSH 隧道连接到 MySQL

mysql - Pentaho 中无法解析的日期错误

java - 如何同步 Solr 导入过程?

Python读取索引不在列表中的HDF5行