5

'interests'と'users_interests'の2つのテーブルがあります。

'users_interests'にはフィールドがuseridありinterestidます。'インタレストにはとがありidますname

共通のインタレストIDが3つ以上あるユーザー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;

コード内の2つの場所でuserid()に基づいて検索を行っていることに注意してください。2

于 2010-08-14T22:29:33.310 に答える
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が必要な場合は、必要な4つの結合をテーブルに追加し、関連する列をSELECT句に追加できると確信しています。

于 2010-08-14T21:58:45.150 に答える