【发布时间】:2013-02-21 18:58:00
【问题描述】:
考虑一个具有以下架构的 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>;
所以我正在考虑这样的 2 列上的复合索引:
index(user_id, following_user_id)
与
index(following_user_id, user_id)
1) 索引是根据需要创建的,但是当记录很多(〜百万)时它们会起作用吗?
2) 索引会在正确的时间使用正确的索引来加速查询吗?
PS:我不需要sort/range selection 查询,只需要直接匹配查询。有没有更好的索引方案可以满足这个要求?
【问题讨论】:
-
你应该提取你的查询的解释,但我几乎可以肯定只需要一个索引并且会自己处理这两种组合
-
我知道第二个查询可以这样写:
select * from table where user_id = <y> and following_user_id = <x>。但我的业务/应用程序逻辑需要这种冗余 -
索引应该可以工作。如果您始终在 where 条件中使用这两个字段,则只需要一个复合索引。您的两个查询都将使用它。 WHERE 子句的顺序无关紧要。
-
@Tom
where的顺序确实很重要,并且直接取决于索引的定义方式。请参阅@Gordon 的答案以获得更广泛的解释 -
@Arindam 不,不,不。您编写
WHERE的方式无关紧要。WHERE user_id = <y> AND following_user_id = <x> AND和WHERE following_user_id = <x> AND user_id = <y>100% 等效,将使用 2 个索引中的任何一个。
标签: mysql indexing composite-index