2016-06-07 68 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,