考虑具有以下架构的 MySql 表
+-------------------+------------+------+-----+-
| Field | Type | Null | Key |
+-------------------+------------+------+-----+-
| id | int(11) | NO | PRI |
| user_id | int(11) | YES | MUL |
| following_user_id | int(11) | NO | MUL |
+-------------------+------------+------+-----+-
现在我需要像这样的查询
select * from table where user_id = <x> and following_user_id = <y>;
还有
select * from table where following_user_id = <x> and user_id = <y>;
所以我正在考虑两列上的复合索引,如下所示:
index(user_id, following_user_id)
并且
index(following_user_id, user_id)
1)索引是根据需要创建的,但是当记录很多(〜数百万)时它们会起作用吗?
2) 在正确的时间使用正确的索引,索引会加速查询吗?
PS:我不需要排序/范围选择
查询,只需要直接匹配查询。有没有更好的索引方案可以满足此要求?
最佳答案
从编译器的角度来看,您的查询是相同的。任何一个索引都可以工作。 where
语句中子句的顺序对于限定索引查询并不重要。
但是,如果存在不等式或只有一个子句,则索引中的顺序会产生影响。
因此,索引 index(user_id, following_user_id)
对于以下情况很有用:
- 直接根据 user_id 进行任何比较(<> 除外)
- user_id = XXX,following_user_id = YYY
- user_id = XXX 和以下_user_id/IN 值
它不会用于:
- following_user_id < YYY
关于mysql - MySql 中的复合索引可以双向工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15010170/