我有2个表,'兴趣'和'users_interests'。
'users_interests'只有userid
和interestid
个字段。
'兴趣只有id
和name
。
我只需要找到共享超过3个兴趣ID的用户ID。我被告知涉及自我加入,但我似乎无法让这个工作。
有人说这样的事情可行:
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
但我没有运气。
答案 0 :(得分:5)
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
)在代码中的两个位置上出现
答案 1 :(得分:2)
你说超过3个共同的兴趣ID ,所以你的意思是“至少4”,对吗?
SELECT first1.userid, second1.userid
FROM users_interests first1, users_interests second1,
users_interests first2, users_interests second2,
users_interests first3, users_interests second3,
users_interests first4, users_interests second4
WHERE
first2.userid=first1.userid AND first3.userid=first1.userid AND first4.userid=first1.userid AND
second2.userid=second1.userid AND second3.userid=second1.userid AND second4.userid=second1.userid AND
first1.userid<>second1.userid AND
first1.interestid=second1.interestid AND
first2.interestid=second2.interestid AND first2.interestid<>first1.interestid AND
first3.interestid=second3.interestid AND first3.interestid<>first2.interestid AND first3.interestid<>first1.interestid AND
first4.interestid=second4.interestid AND first4.interestid<>first3.interestid AND first4.interestid<>first2.interestid AND first4.interestid<>first1.interestid
由于我没有对此进行测试,请记住它可能存在错误,因此只有在您理解的情况下才能使用它。
如果你需要相同的其他共同兴趣,我相信你可以编写代码来动态生成任何数字的查询。此外,如果您需要感兴趣的名称,我相信您将能够将必要的四个联接添加到interests
表并将相关列添加到{{1}条款。