简体   繁体   English

MySQL-为什么此查询不使用索引(据解释)

[英]MySQL - Why doesn't this query use an index (according to explain)

I was playing with EXPLAIN and ran it on this simple query: 我正在使用EXPLAIN并在以下简单查询上运行它:

EXPLAIN SELECT * FROM actions WHERE user_id = 17;

And was quite suprised to see this output: 并很惊讶地看到以下输出:

select_type    SIMPLE
table          actions
type           ALL
possible_keys  user_id
key            null
key_len        null
ref            null
rows           6
extra          Using where

My understanding is this means that no index is being used in the look up, is that correct? 我的理解是,这意味着在查询中没有使用索引,对吗? (There are only 6 rows total in the table at this time, but there will be many more) (此时,表中总共只有6行,但还会有更多行)

The table definition is (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

Why wouldn't this be using the key value on user_id? 为什么不使用user_id上的键值?

Sometimes MySQL does not use an index, even if one is available. 有时,即使索引可用,MySQL也不使用索引。 This is when it would require fewer seeks than reading the table directly. 这是与直接读取表相比需要更少的寻道时。 It seems that with 6 rows you're in this situation. 似乎只有6行,您就处于这种情况。

Remember to periodically run OPTIMIZE TABLE and ANALYZE TABLE when you'll have a more realistic data set. 请记住,当您拥有更实际的数据集时,请定期运行OPTIMIZE TABLEANALYZE TABLE

If you think that you can do a better job than the optimizer, you can use the Index Hint Syntax . 如果您认为自己可以比优化程序做得更好,则可以使用“ 索引提示语法”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM