5

我有 2 张桌子,'interests' 和 'users_interests'。

'users_interests' 只有useridinterestid字段。'利益只有一个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

但我没有运气。

4

2 回答 2

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在代码中的两个位置基于 ( ) 进行搜索

于 2010-08-14T22:29:33.310 回答
2

您说的共同兴趣 ID 超过 3 个,所以您的意思是“至少 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表中并将相关列添加到SELECT子句中。

于 2010-08-14T21:58:45.150 回答