如何计算MySQL中的相似兴趣

如何计算MySQL中的相似兴趣,mysql,sql,join,inner-join,self,Mysql,Sql,Join,Inner Join,Self,我有两个表格,“兴趣”和“用户兴趣” “users\u interests”只有userid和interestid字段。 “兴趣只有一个id和一个名字 我只需要找到有3个以上共同兴趣ID的用户ID。我被告知涉及到自连接,但我似乎无法让它起作用 有人说这样的方法可以奏效: SELECT others.userid FROM interests AS user JOIN interests AS others USING(interestid) WHER

我有两个表格,“兴趣”和“用户兴趣”

“users\u interests”只有userid和interestid字段。 “兴趣只有一个id和一个名字

我只需要找到有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
但是我没有运气。

你说有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
因为我还没有测试过这个,请记住它可能有错误,所以只有在您理解它的情况下才能使用它

如果您需要对其他共同感兴趣的数字进行相同的查询,我相信您可以编写代码来为任何数字动态生成此查询。另外,如果您需要兴趣名称,我相信您可以将必要的四个连接添加到兴趣表中,并将相关列添加到SELECT子句中

注意出现了userid,我们在代码中的两个地方根据2进行搜索

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;