Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql解释表明,当查询不应该根据Mysql文档时,它使用的是索引_Mysql_Indexing_Explain - Fatal编程技术网

Mysql解释表明,当查询不应该根据Mysql文档时,它使用的是索引

Mysql解释表明,当查询不应该根据Mysql文档时,它使用的是索引,mysql,indexing,explain,Mysql,Indexing,Explain,我在事务表上创建了一个mysql多列索引。此索引使用my rails模式中描述的3列: add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree 现在我有了这个活动记录查询: MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATC

我在事务表上创建了一个mysql多列索引。此索引使用my rails模式中描述的3列:

  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和多列索引:

如果表具有多列索引,则 优化器可以使用索引查找行。例如,如果 你有一个三列索引(col1,col2,col3),你有索引 (col1)、(col1,col2)和(col1,col2,col3)上的搜索功能。 有关详细信息,请参阅“多栏” 索引”

对我来说,这意味着前面的查询不应该使用前面的索引

但是,当我在查询
MerchantTransaction.where(参考:“2-9020”,种类:“放置批次”)上运行EXPLAIN时,
键下的EXPLAIN
,我通过_reference _parent _ref _kind
获得
,在
Extra
列下,我有
使用索引条件
,这似乎意味着实际使用了索引


这是怎么可能的?

它将使用索引,因为您在查询(
参考
)中列出了最左边的列,即来自文档的用例(col1)。条件(
kind
)中的另一列未通过索引进行搜索。

给定

WHERE reference = '...' AND kind = '...'

优化器可以使用索引,但只能使用
引用
部分

另一方面,如果查询中提到的只有这三列,那么该索引是“覆盖的”,因此优化器有另一个理由使用该索引

请提供
解释选择…
。在
Key\u len
列中,它将提示仅使用
reference
。在
Extra
列中,
使用索引是它“覆盖”的线索

对于当前查询,这是一个更好的索引,但对于其他一些查询可能更糟:

INDEX(reference, kind, parent)
INDEX(reference, kind, parent)