2010-08-14 59 views
5

我有2個表,'interest'和'users_interests'。如何計算MySQL中的類似興趣點

'users_interests'只有useridinterestid字段。 的興趣只有一個id和一個name

我只需要找到具有超過3個利息ID的userid's共同點。我被告知有一個自我加入參與,但我似乎無法得到這個工作。

有人說這樣的事情可以工作:

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 

但我與它有沒有運氣。

回答

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; 

注意兩個地方,我們正在對我們的基礎搜索userid2)的代碼的發生

+0

驚人!謝謝你,這個作品非常漂亮! – Ryan 2010-08-15 07:21:09

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表中,並將相關列添加到SELECT子句中。