我有一个非常简单的查询:
SELECT comments.*
FROM comments
WHERE comments.imageid=46
这是我的 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 ;
但是MySql 不能在这个简单的查询上使用索引。这是解释结果:
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 可以使用索引。为什么? :
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 正在执行全表扫描而不是在你的第一个查询中使用索引。估计全表扫描的代价可能比先匹配索引再查行的代价要低。
在您的第二个查询中使用索引,因为可以直接从索引中获取查询的所有列(“id”列),而无需在匹配索引后查找表行。这就是“使用索引”额外信息的含义。
尝试如果“注释”中有大量行,MySQL 仍然使用完整扫描,我认为这将是一种奇怪的行为。事实上,我已经在 MySQL 5.1 版中进行了完全相同的测试,即使只有几行,它也始终使用“索引”。
关于mysql - 我的简单 MySql 查询不使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160694/