我有 2 个表,'interests' 和 'users_interests'。
'users_interests' 只有 userid
和 interestid
字段。
'interests 只有一个 id
和一个 name
。
我只需要找到具有超过 3 个共同兴趣 ID 的用户 ID。有人告诉我,涉及到 self 加入,但我似乎无法让它发挥作用。
有人说这样的东西可以工作:
SELECT
others.userid
FROM interests AS user
JOIN interests AS others
USING(interestid)
WHERE user.userid = 2
GROUP BY
others.userid
ORDER BY COUNT(*) DESC
但我没有运气。
最佳答案
SELECT ui.userid, COUNT(*) AS common_interests
FROM users_interests ui
WHERE ui.interestid IN (
SELECT ui2.interestid FROM users_interests ui2 WHERE ui2.userid = 2
)
AND ui.userid <> 2
GROUP BY ui.userid
HAVING common_interests > 3;
请注意 userid
的出现,我们的搜索基于 (2
) 在代码中的两个位置
关于mysql - 如何计算MySQL中的相似兴趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3485257/