如何在MySQL中为SELECT查询创建多对多关系表?

时间:2017-10-02 11:46:01

标签: mysql sql

用户可以有很多兴趣。 兴趣可能对许多用户感兴趣。 我的数据库看起来像这样:

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_id interest_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;

2 个答案:

答案 0 :(得分:1)

这是一个查询,它将找到所有具有兴趣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;

答案 1 :(得分: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);