我有两张这样的桌子:
用户:
user_id|user_name
兴趣:
user_id|interest_id|interest_name
例如,“兴趣”的填入方式如下:
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 (...)知道怎么解决这个问题吗?
我也许会先把我的兴趣读入数组,然后再做循环什么的?
谢谢!
发布于 2016-06-07 20:42:15
在我看来,你想要的是userID,计数和列表(Interest_name)
因此,我们只需要将兴趣加入到interest_ID上,然后通过“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发布于 2016-06-07 20:08:00
你可能需要一个计数(*)和分组
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, https://stackoverflow.com/questions/37688272
复制相似问题