如何使MySQL中的多对多关系表对SELECT查询有效?
用户可以有很多兴趣。 一种兴趣可能会引起许多用户的兴趣。 我的数据库如下所示:如何使MySQL中的多对多关系表对SELECT查询有效?,mysql,sql,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) in
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)
如何改进用户兴趣表以便能够有效地选择所有具有相同兴趣的用户user\u id和interest\u 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;
下面是一个查询,它将查找所有感兴趣的用户1和2。应该清楚如何将其推广到任意数量的Interet。子查询对用户进行聚合,并查找具有我们想要的兴趣的用户。然后我们将其连接回
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;
获取用户兴趣#3的查询非常简单(在中使用
或存在
)。在users\u to\u interest(interest\u id,user\u id)
上有一个索引,这应该非常快
select *
from users
where id in (select user_id from users_to_interests where interest_id = 3);
您需要一个关于(兴趣id,用户id)
和(用户id,兴趣id)
的索引,用于您可能进行的所有查询。您能否详细说明相同兴趣的含义?您是在寻找精确匹配、部分重叠还是其他内容?您可以通过删除id字段并将其他两个字段作为主键来改进users\u to\u interests表。除此之外,这将自动为它们编制索引。@TimBiegeleisen,我已经添加了一个我想要的示例reach@GordonLinoff我没有数据库体系结构方面的经验。你能给我一个更详细的答案和例子吗?或者给我一个链接,我可以在哪里找到这些信息?谢谢你的回答。它使用索引吗?我应该在之前向兴趣id和用户id字段添加索引吗?我不知道,当我进行查询时是否需要提及索引,或者SQL默认情况下会使用它们?实际上,我不理解索引的这个概念。我知道,当我使用索引时,SQL将使用类似于二进制搜索的东西来搜索select查询。但是,我不明白应该将SQL查询更改为使用索引,否则查询将保持不变。架构中索引的存在不依赖于任何特定的查询。在兴趣点.title
和用户到兴趣点.用户id
上添加索引可能会有所帮助。但是我不认为索引会改变我的方法的整体逻辑。但是多重兴趣呢?@Tim Biegeleisen:要么在
子句中有两个,要么最好将上面的子查询更改为具有
的聚合查询。但是,在请求中,建议的查询都只针对一个兴趣,因此这里甚至不需要针对多个兴趣的查询。