2012-08-09 56 views
1

我在数据库中有一个表'posts',它在user_id(键:MUL)上有非唯一索引。MySQL:'EXPLAIN'显示对类似查询的不同解释

mysql> show columns from posts; 
+---------+--------------+------+-----+-------------------+----------------+ 
| Field | Type   | Null | Key | Default   | Extra   | 
+---------+--------------+------+-----+-------------------+----------------+ 
| id  | int(11)  | NO | PRI | NULL    | auto_increment | 
| user_id | int(11)  | YES | MUL | NULL    |    | 
| post | varchar(140) | NO |  | NULL    |    | 
+---------+--------------+------+-----+-------------------+----------------+ 

此表,解释给预期的解释,其中类型是“REF

mysql> explain select * from posts where posts.user_id=1; 
+----+-------------+-------+------+---------------+---------+---------+-------+------+-------------+ 
| id | select_type | table | type | possible_keys | key  | key_len | ref | rows | Extra  | 
+----+-------------+-------+------+---------------+---------+---------+-------+------+-------------+ 
| 1 | SIMPLE  | posts | ref | user_id  | user_id | 5  | const | 74 | Using where | 
+----+-------------+-------+------+---------------+---------+---------+-------+------+-------------+ 

我有第二个表“追随者”,其中“USER_ID”和“跟随”是不一部分-unique指数

mysql> show columns from followers; 
+---------------+-----------+------+-----+---------------------+----------------+ 
| Field   | Type  | Null | Key | Default    | Extra   | 
+---------------+-----------+------+-----+---------------------+----------------+ 
| id   | int(11) | NO | PRI | NULL    | auto_increment | 
| user_id  | int(11) | YES | MUL | NULL    |    | 
| follower  | int(11) | YES | MUL | NULL    |    | 
+---------------+-----------+------+-----+---------------------+----------------+ 

但在该表中,类型为 'ALL'。我预计它'REF'与上表中的'user_id'类似,这个'user_id'也有非唯一索引。这有什么解释吗?

mysql> explain select * from followers where followers.user_id=1; 
+----+-------------+-----------+------+---------------+------+---------+------+------+-------------+ 
| id | select_type | table  | type | possible_keys | key | key_len | ref | rows | Extra  | 
+----+-------------+-----------+------+---------------+------+---------+------+------+-------------+ 
| 1 | SIMPLE  | followers | ALL | user_id  | NULL | NULL | NULL | 6 | Using where | 
+----+-------------+-----------+------+---------------+------+---------+------+------+-------------+ 
+0

很可能是因为第二个表具有来自'(user_id,follower)'的组合键。请发布'show create table followers' – favoretti 2012-08-09 12:06:33

+0

我希望@favoretti是正确的。 – 2012-08-09 12:57:31

回答

2

我会将它作为答案发布,因为我非常确定是这种情况。

我想你会得到不同,因为在followers表中,您有一个user_idfollower字段的复合关键字,而不仅仅是user_id上的一个关键字。

因此,索引将用于在WHERE子句中同时使用user_idfollower的查询。

user_id字段中添加单独的索引,您将得到相同的解释。