2016-06-07 67 views
0

我有2個表是這樣的:支持按用戶興趣相投

用戶:

USER_ID | USER_NAME

利益:

USER_ID | interest_id | INTEREST_NAME

例如'interest'就是這樣填充的:

123|1|Football 
123|2|Swimming 
123|3|Skiing 
456|2|Swimming 
... 

現在我是(user_id 123)登錄,我想知道誰像我這樣最常見的興趣(排序降序)。

結果應該是這樣的:

User 1: 45 interests in common (and list them) 
User 2: 23 interests in common (...) 
User 3: 11 interests in common (...) 

不知道如何解決這個問題?

我也許會首先將我的興趣讀入一個數組,然後做一個循環或什麼?

謝謝!

+0

你試過了什麼?請閱讀[我可以問哪些主題](http://stackoverflow.com/help/on-topic) 和[如何提出一個好問題](http://stackoverflow.com/help/how-to-問) 和[完美的問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) SO是**不是免費的編碼或代碼轉換或教程或圖書館尋找服務**您還必須證明您已經努力解決您自己的問題。 – RiggsFolly

回答

1

的方式我看它,你想要的用戶ID,計數和列表(INTEREST_NAME)

所以我們只需要加入利益以interest_ID爲基礎,然後通過「我的興趣」(123)進行限制,並使用簡單聚合和group_concat來獲取列表。

SELECT OI.User_ID 
    , count(Distinct OI.Interest_ID) CommonInterestCount 
    , Group_concat(OI.Interest_name) InterestList 
FROM interests MyI 
LEFT JOIN interests OI 
    on OI.Interest_ID = MyI.Interest_ID 
WHERE MyI.user_ID = '123' 
GROUP BY OI.user_ID 
1

可能是你需要一個COUNT(*)和組由

select interests.user_id, interests.count(*) , users.user_name 
from interests 
inner join users on users.user_id = interests.user_id 
where interest_id in (select interest_id from interests where user_id = 123) 
group by interests.user_id,