SQL:根据具有共同值的单元格对返回行

时间:2019-05-04 07:08:43

标签: mysql sql

我有一个社交媒体,例如数据库,用户可以互相关注,用户也可以有兴趣。 我想知道如何返回列出彼此关注且至少具有共同兴趣的用户的行。

我编写了查询,以显示彼此关注的用户以及正在关注的用户感兴趣的内容。我需要隔离彼此关注并且对同一事物感兴趣的用户对。< / p>

代码如此之遥:

SELECT me.followed, me.following, me.interest FROM 
    (SELECT followed, following, interest
    FROM follow JOIN interest
    WHERE followed = interest.user_id
    ORDER BY followed) AS me
INNER JOIN follow AS you ON me.following = you.followed
WHERE me.followed = you.following

[表格] https://i.imgur.com/t68T4OI.png

 A   B C 
 2   1 2 
 2   1 6 
 2   1 9 
 1   2 1 
 1   2 7 
 1   2 8 
 7  15 1 
 7  15 7 
 15  7 2
 15  7 7 

(A =关注,B =关注,C =用户兴趣) 抱歉,格式化似乎没有简单的方法来制作表格。

到目前为止,我的表格显示用户2跟随用户1,用户1跟随用户2。与用户15和7相同。它还显示用户2对兴趣2,兴趣6和兴趣9感兴趣。

我想编写一些仅返回用户7和用户15的代码,因为它们是唯一的彼此关注并具有共同兴趣(兴趣7)的用户,但是我不确定从哪里开始。 / p>

3 个答案:

答案 0 :(得分:2)

如果我被误解了,我不会知道,但是仅user_follow表可以回答这个查询吗?

SELECT * FROM
  user_follow a 
  INNER JOIN 
  user_follow b
  ON
    a.followed_user_id = b.following_user_id AND
    a.following_user_id = b.followed_user_id AND
    a.interest_id = b.interest_id

答案 1 :(得分:1)

您需要再次加入user_interest

SELECT me.followed_user_id, me.following_user_id, 
   me.interest_id AS 'same interest id'
FROM user_follow AS me
JOIN user_follow AS you -- me and you follow each other
  ON me.following_user_id = you.followed_user_id
 AND me.followed_user_id = you.following_user_id
JOIN user_interest AS me_int -- my interest
ON me.following_user_id = me_int.user_id
JOIN user_interest AS you_int -- your interest
  ON me.followed_user_id = you_int.user_id
 AND me_int.interest_id = you_int.interest_id --must be the same

答案 2 :(得分:0)

如果我正在编写此查询,则需要一个结果集,其中成对的用户仅出现一次,并且有很多共同点。

所以:

select uf.followed_user_id, uf.following_user_id,
       count(*) as interests_in_common
from user_follow uf join
     user_interest uifed
     on uifed.user_id = uf.followed_user_id join
     user_interest uifing
     on uifing.user_id = uf.followed_user_id and
        uifing.interest_id = uifed.interest_id
where (uf.followed_user_id, uf.following_user_id) in
          (select uf2.following_user_id, uf2.followed_user_id
           from user_follow uf2
          ) and
      uf.followed_user_id < uf.following_user_id
group by uf.followed_user_id, uf.following_user_id;