用户:
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 (...)
知道如何解决这个问题吗?
我或许首先将我的兴趣读入一个数组然后做一个循环或什么?
谢谢!
答案 0 :(得分:1)
您可能需要计数(*)和分组
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,
答案 1 :(得分:1)
我看到它的方式你想要userID,count和list(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