mysql - Mysql Explain shows that query is using index when it shouldnt be according to Mysql doc
问题描述
I created a mysql multi column index on a transactions table. This index uses 3 columns as described in my rails schema :
add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree
Now I have this active record query :
MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")
which in pure sql gives :
"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"
Now from what I read about mysql and multi column indexing :
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”.
To me, this means that the precedent query shouldnt be using the previous index.
However when I run EXPLAIN on my query MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain
under the key
column, I get by_reference_parent_ref_kind
and under the Extra
column I have Using index condition
which seems to imply that the index is actually used.
How is that possible ?
解决方案
它将使用索引,因为您在查询 ( reference
) 中列出了最左边的列,即文档中的用例 (col1)。kind
不通过索引搜索条件 ( ) 中的另一列。
推荐阅读
- javascript - 打开汉堡菜单
- javascript - 使用可变参数时的 JavaScript drawImage 加载问题
- ios - 如何在全局工具栏项上设置 Inset?
- java - 当只需要一个实例时,总是使用单例是否有意义?
- java - 当返回类型为字符串时,我是否还需要在 if-else 条件之外返回字符串
- javascript - 如果文本与提供的对象匹配,则超链接文本
- mongodb - 使用 mgo 对 mongoDB 中的嵌入文档进行部分更新
- spring - Spring REST:简单 REST 请求上的 404
- python - Python:将字符串列表转换为布尔值,其中布尔值以字符串形式存在
- apache-spark - 为什么 spark-sql cpu 利用率高于 hive?