我有一個非常簡單的查詢:我簡單的MySQL查詢不使用索引
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不能在這個簡單的查詢使用索引。這裏是解釋結果:
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
它不是*「但MySql **不能**使用索引」*。它是:「但MySql **不會**使用索引」。 'possible_keys = ids'和'key = NULL'表明使用索引被優化器檢查並被拒絕。全表掃描被認爲是更快 - 它可能是在你的情況。 – 2012-04-15 09:54:13