MySQL SELECT IN() statement and InnoDB Index fails
I have a query that does this:
SELECT `threaded_comments`.* FROM `threaded_comments` WHERE `threaded_comments`.`parent_id` IN (4, 5)
I've also setup an INDEX on the parent_id column.
When I do a EXPLAIN SELECT check on the query I get the following information:
`select_type`,`table`,`type`,`possible_keys`,`key`,`key_len`,`ref`,`rows`,`Extra`
'SIMPLE', 'threaded_comments', 'ALL', 'COMMENT_PARENT', NULL, NULL, NULL, 3, 'Using where'
Looks like no keys are being used for the where clause of the index. However, when I do a simple parent_id = 4 then it works. But when I do parent_id=4 or parent_id=5 then it brings up the same message.
I figured out that it has todo with the innoDB database table type. MySQL seems to not like it when there are IN ope开发者_如何学JAVArations performed on that specific database engine. Could this be a problem with the EXPLAIN tool or it is something that InnoDB is missing?
No, it has nothing to do with InnoDB. Your EXPLAIN plan shows that the query is able to use the index, but MySQL optimizer decided not to use it. The selected decision depends on many factors. But later when your table grows up, the optimizer can make a different decision if it thinks it's useful. If you want to explicitly use an index on that query then you may try to force index.
It seems that you have too less rows in tables and full scan is preferable.
Index is not always a benefit.
From the documentation:
Each table index is queried, and the best index is used unless the optimizer believes that it is more efficient to use a table scan. At one time, a scan was used based on whether the best index spanned more than 30% of the table, but a fixed percentage no longer determines the choice between using an index or a scan. The optimizer now is more complex and bases its estimate on additional factors such as table size, number of rows, and I/O block size.
In your case, index is considered fine for parent_id = 4
but a table scan is preferred for parent_id IN (4, 5)
精彩评论