【问题标题】:Sort users by similar interests按相似兴趣对用户进行排序
【发布时间】:2016-06-07 20:01:06
【问题描述】:

我有 2 个这样的表:

用户:

user_id|用户名

兴趣:

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 (...)

知道如何解决这个问题吗?

我可能会先将我的兴趣读入一个数组,然后再做一个循环之类的?

谢谢!

【问题讨论】:

标签: mysql


【解决方案1】:

在我看来,你想要用户 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

【讨论】:

    【解决方案2】:

    你可能需要一个计数(*)和分组

     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, 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2013-09-15
      • 2020-09-14
      • 2012-08-14
      • 2018-01-13
      • 2016-08-01
      • 1970-01-01
      相关资源
      最近更新 更多