My simple MySql query doesn't use index

此生再无相见时 提交于 2020-01-01 09:11:05

问题


I have a very simple query:

  SELECT   comments.*
  FROM comments 
  WHERE comments.imageid=46

And this is my table:

CREATE TABLE IF NOT EXISTS `comments` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `imageid` int(10) unsigned NOT NULL DEFAULT '0',
  `uid` bigint(20) unsigned NOT NULL DEFAULT '0',
  `content` text CHARACTER SET utf8,
  `adate` datetime DEFAULT NULL,
  `ip` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ids` (`imageid`) USING BTREE,
  KEY `dt` (`adate`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

But MySql can't use index on this simple query. here is the explain result:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    filtered    Extra
1   SIMPLE  comments    ALL     ids     NULL    NULL    NULL    4   75.00   Using where

while I change the query to this, Mysql can use index. Why? :

  SELECT   comments.id
  FROM comments 
  WHERE comments.imageid=46

here is the explain:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    filtered    Extra
1   SIMPLE  comments    ref     ids     ids     4   const   4   100.00  Using index

回答1:


I guess that you have few rows in 'comments' table, this is why MySQL is doing a full table scan instead of using the index in your first query. It's estimating that the cost of a full table scan may be lower than first match the index and then lookup the rows.

In your second query is using the index because it is possible to get all the columns of the query (the 'id' column) directly from the index with no need to lookup the table rows after matching the index. This is the meaning of "Using index" extra information.

Try if with a significant number of rows in 'comments' MySQL still uses a full scan, I think that it would be a strange behaviour. In fact, I've tested exactly the same in a MySQL version 5.1 and it's always using the 'index' even with few rows.




回答2:


Did you try the standard sort of things?




回答3:


The second query is an index-covered query. The whole information requested can be read from the index (since the primary key is part of any secondary index in InnoDB).

In the first query MySQL has to read the PKs from the index, then to read the rows. Because table has so small amount of rows, optimizer decides that it would be faster if it reads rows directly and discard the ones that do not match



来源:https://stackoverflow.com/questions/10160694/my-simple-mysql-query-doesnt-use-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!