我的简单MySql查询不使用索引 [英] My simple MySql query doesn't use index

查看:132
本文介绍了我的简单MySql查询不使用索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的查询:

I have a very simple query:

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

这是我的表:

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 ;

但是MySql不能在这个简单的查询中使用索引。这里是解释结果:

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

当我将查询更改为此时,Mysql可以使用索引。为什么? :

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

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

这里是解释:

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


推荐答案

我猜你在'comments'表中有几行,这就是为什么MySQL正在进行全表扫描而不是在第一次使用索引查询。它估计全表扫描的成本可能低于第一次匹配索引,然后查找行。

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.

在第二个查询中使用索引,因为它是可以直接从索引中获取查询的所有列('id'列),而不需要在匹配索引后查找表行。这就是使用索引额外信息的含义。

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.

尝试在评论中使用大量行仍然使用完全扫描,我认为这将是一种奇怪的行为。事实上,我在MySQL版本5.1中测试的完全相同,即使只有很少的行,它总是使用'​​索引'。

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.

这篇关于我的简单MySql查询不使用索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆