【问题标题】:How to make many to many relationship table efficient for SELECT queries in MySQL?如何使多对多关系表对 MySQL 中的 SELECT 查询有效?
【发布时间】:2017-10-02 11:46:01
【问题描述】:

一个用户可以有很多兴趣。 许多用户可能对一个兴趣感兴趣。 我的数据库是这样的:

Users table:
      id - primary key,
      name,
      email,

Interests table:
      id - primary key,
      title

Users_To_Interests table:
      id - primary key,
      user_id(id from users table)
      interest_id(id from interests table)

如何改进 Users_To_Interests 表以便能够有效地挑选出所有具有相同兴趣的用户? user_idinterest_id 列没有索引或键。如果我需要添加它们,请告诉我该怎么做。

第 1 版:例如,

user1 has interests : interest1, interest2, interest3;
user2 has interests : interest3, interest4;
user3 has interests : interest3, interest5;
user4 has interests : interest4;

If I want to get all users who have interest1, I should receive user1;
If I want to get all users who have interest2, I should receive user1;
If I want to get all users who have interest3, I should receive user1, user2, user3;

【问题讨论】:

  • 您希望在(interest_id, user_id)(user_id, interest_id) 上为您可能进行的所有查询建立索引。
  • 您能详细说明一下您所说的相同兴趣是什么意思吗?您是否在寻找完全匹配、部分重叠或其他内容?
  • 您可以通过删除 id 字段并将其他两个字段作为主键来改进 users_to_interests 表。除其他外,这应该会自动为它们编制索引。
  • @TimBiegeleisen,我添加了一个我想要达到的示例
  • @GordonLinoff 我没有数据库架构方面的经验。您能否通过示例给我更多扩展答案或给我一个链接,我在哪里可以找到此信息?

标签: mysql sql


【解决方案1】:

获取用户兴趣#3 的查询非常简单(使用INEXISTS)。使用users_to_interests(interest_id, user_id) 上的索引,这应该非常快。

select *
from users
where id in (select user_id from users_to_interests where interest_id = 3);

【讨论】:

  • 但是多重兴趣呢?
  • @Tim Biegeleisen:两个IN 子句或更好地将上面的子查询更改为带有HAVING 的聚合查询。但是,在请求中,建议的查询都只针对一个兴趣,因此这里甚至不需要针对多个兴趣的查询。
【解决方案2】:

这是一个查询,它将找到所有具有兴趣 1 和 2 的用户。应该清楚如何将其推广到任意数量的兴趣。子查询聚合用户并找到那些有我们想要的兴趣的用户。然后,我们将其连接回Users 表,以获取每个用户的完整信息。

SELECT
    t1.*
FROM Users t1
INNER JOIN
(
    SELECT ui.user_id
    FROM Users_To_Interests ui
    INNER JOIN Interests i
        ON ui.interest_id = i.id
    WHERE i.title IN ('interest2', 'interest3')
    GROUP BY ui.user_id
    HAVING COUNT(DISTINCT i.id) = 2
) t2
    ON t1.id = t2.user_id;

【讨论】:

  • 谢谢您的回答。它使用索引吗?我之前应该为interest_id 和user_id 字段添加索引吗?我不知道,如果我在进行查询时需要以某种方式提及索引,或者 SQL 默认会使用它们?实际上,我不了解索引的这个概念。我明白,当我使用索引时,SQL 将使用类似于二进制搜索的方式来进行选择查询。但是,我不明白我应该将 SQL 查询更改为使用索引,否则查询将保持不变。
  • 架构中是否存在索引不依赖于任何特定查询。在我的脑海中,在Interests.titleUsers_To_Interests.user_id 上添加索引可能会有所帮助。但我认为索引不会改变我的方法的整体逻辑。
猜你喜欢
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2020-09-02
相关资源
最近更新 更多