我在数据库中有一个表‘post’,它在user_id上有非唯一的索引(键: MUL)。
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‘和’追随者‘是非唯一索引的一部分。
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 |
+----+-------------+-----------+------+---------------+------+---------+------+------+-------------+发布于 2012-08-09 12:09:11
我会把它作为答案发出去,因为我很确定情况就是这样。
我认为您有差异,因为在followers表中,您有一个来自user_id和follower字段的复合键,而不仅仅是user_id上的一个键。
因此,索引将用于在user_id子句中同时使用follower和follower的查询。
在user_id字段中添加一个单独的索引,您将得到相同的解释。
https://stackoverflow.com/questions/11882976
复制相似问题