简体   繁体   中英

MySQL isn't using the right index

I'm trying to understand why MySQL doesn't use the right index.

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

Index02 => (id_user,hour,created_at)

I will do two kind of queries:

1) where id_user=xxx

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).

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. 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%.

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. "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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