开发者

MySQL won't use index for query?

I have this table:

CREATE TABLE `point` (                                                                                 
          `id` INT(11) NOT NULL AUTO_INCREMENT,                                                                
          `siteid` INT(11) NOT NULL,                                                                           
          `lft` INT(11) DEFAULT NULL,                                                                          
          `rgt` INT(11) DEFAULT NULL,                                                                          
          `level` SMALLINT(6) DEFAULT NULL,                                                                    
          PRIMARY KEY  (`id`),                                                                                 
          KEY `point_siteid_site_id` (`siteid`),                                                               
          CONSTRAINT `point_siteid_site_id` FOREIGN KEY (`siteid`) REFERENCES `site` (`id`) ON DELETE CASCADE  
        ) ENGINE=INNODB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci        

And this query:

SELECT * FROM `point` WHERE siteid = 1;

Which results in this EXPLAIN information:

+----+-------------+-------+------+----------------------+------+---------+-----开发者_如何学运维-+------+-------------+
| id | select_type | table | type | possible_keys        | key  | key_len | ref  | rows | Extra       |
+----+-------------+-------+------+----------------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | point | ALL  | point_siteid_site_id | NULL | NULL    | NULL |    6 | Using where |
+----+-------------+-------+------+----------------------+------+---------+------+------+-------------+

Question is, why isn't the query using the point_siteid_site_id index?


I haven't used MySQL much, but in PostgreSQL if the number of records is small in the table, it can decide not to use the index. This is not a problem, because it chooses the best query plan for the situation. When the number of records is bigger, it will use the index. Maybe this is the same case here with MySQL.

Edit: Are you sure the foreign key is indexed?


It's probably because you don't have enough sample data, or the cardinality (diversity) of the siteid values isn't very large. These are the most common reasons the optimizer will find it quicker just to read all the values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜