我在数据库中有一个表'posts',它在user_id(Key: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 ”。我预计它与前一个表中的'user_id'类似' REF ',这个'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 :(得分:2)
我会把它作为答案发布,因为我很确定是这种情况。
我认为您会产生差异,因为在followers
表中,您有来自user_id
和follower
字段的复合键,而不仅仅是user_id
上的键。
因此,索引将用于在user_id
子句中同时使用follower
和WHERE
的查询。
在user_id
字段上添加单独的索引,您将得到相同的解释。