我正在玩EXPLAIN并在这个简单的查询上运行它:
EXPLAIN SELECT * FROM actions WHERE user_id = 17;
Run Code Online (Sandbox Code Playgroud)
看到这个输出很惊讶:
select_type SIMPLE
table actions
type ALL
possible_keys user_id
key null
key_len null
ref null
rows 6
extra Using where
Run Code Online (Sandbox Code Playgroud)
我的理解是这意味着在查找中没有使用索引,这是正确的吗?(此时表中总共只有6行,但会有更多行)
表定义是(inpart):
CREATE TABLE `actions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
...
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1
Run Code Online (Sandbox Code Playgroud)
为什么不使用user_id上的键值?
有时MySQL不使用索引,即使有索引也是如此.这是因为它比直接阅读表需要更少的搜索.似乎有6行你就是这种情况.
当您拥有更真实的数据集时,请记住定期运行OPTIMIZE TABLE和ANALYZE TABLE.
如果您认为可以比优化器做得更好,则可以使用索引提示语法.