简体   繁体   English

MySQL没有使用正确的索引

[英]MySQL isn't using the right index

I'm trying to understand why MySQL doesn't use the right index. 我试图理解为什么MySQL不使用正确的索引。

tb_msgs tb_msgs

id int PK
id_user int
id_user_friend int
sent bool
hour int
created_at date

I created two index: 我创建了两个索引:

Index01 => (id_user,id_user_friend) unique Index01 => (id_user,id_user_friend) unique

Index02 => (id_user,hour,created_at) Index02 => (id_user,hour,created_at)

I will do two kind of queries: 我将进行两种查询:

1) where id_user=xxx 1) where id_user=xxx

2) where id_user=xxx and hour=x and created_at=curdate() and sent=1 2) where id_user=xxx and hour=x and created_at=curdate() and sent=1

The first one uses the right index ( index01 ) but for the second one, if and sent=1 is there, then MySQL doesn't use any index - but without and sent=1 MySQL uses the right index (index02). 第一个使用正确的索引( index01 ),但第二个使用if and sent=1 ,则MySQL不使用任何索引-但不使用and sent=1 MySQL使用正确的索引(index02)。

Could someone give me the reason? 有人可以给我原因吗?

When you add a condition on sent to the WHERE clause, you will have to access the base table to evaluate that condition since it is not part of index02. 当您将条件添加到sent到WHERE子句时,您将必须访问基表以评估该条件,因为它不是index02的一部分。 If many rows satisfies the condition, it may be more efficient to scan the entire table instead of using the index. 如果有许多行满足该条件,则扫描整个表而不是使用索引可能更有效。 As a rule of thumb, the break point is around 15%. 根据经验,断点约为15%。

Another explanation is that it is actually using the index, but that you interpret the lack of "Using index" in Extra column of EXPLAIN as an indication that index is not used. 另一个解释是它实际上正在使用索引,但是您将EXPLAIN的Extra列中缺少“使用索引”解释为未使用索引的指示。 "Using index" should be interpreted as "Using only index", ie, the base table is not accessed at all. “使用索引”应解释为“仅使用索引”,即根本不访问基表。 Whether an index is used or not, can be seen from the column key of EXPLAIN. 从EXPLAIN的列key可以看到是否使用索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM