获取共同好友的Sql查询

时间:2021-03-22 22:20:39

标签: mysql sql node.js

我有两个表,一个叫做用户(id,first name,last name...)第二个叫做 follows,其中包含有关哪个用户关注其他用户的数据

下表示例

userId   followerId
6           10
6           2
6           3
8           1
8           2
8           3

如何获取两个用户的共同好友数量

预期结果应该是

first_user second_user num_of_mutual_friends
    83          73               3

4 个答案:

答案 0 :(得分:0)

WITH firstUser AS (
    SELECT followerId
    FROM followings
    WHERE userId = 6 
)
, secondUser AS (
    SELECT followerId
    FROM followings
    WHERE userId = 8 
)

SELECT COUNT(followerId)
FROM firstUser
INNER JOIN secondUser ON firstUser.followerId = secondUser.followerId

答案 1 :(得分:0)

有多种方法可以实现您的愿望,但这应该可以解决问题:

select
  f.userId as first_user,
  s.userId as second_user,
  count(*) as num_of_mutual_friends
from
  followings f
  inner join followings s on s.followerId = f.followerId
                         and s.userId = 6
where
  f.userId = 8
group by
  f.userId,
  s.userId

您可以查看 here 一个工作示例。

答案 2 :(得分:0)

从用户加入以下两个:

select u.*
from users
join followings a on a.followerId = u.id
  and a.userid = 6
join followings b on b.followerId = u.id
  and b.userid = 8

答案 3 :(得分:0)

您也可以使用子查询来做到这一点。因此,如果您想获取 id 为 8 的用户和 id 为 6 的用户之间相互关注的人数,您可以使用:

解决方案 1:

SELECT COUNT(followerId) AS mutual_followers_count FROM followings WHERE userId = 6 AND followerId IN (SELECT followerId FROM followings WHERE userId = 8)

解决方案 2:

SELECT COUNT(DISTINCT(followerId)) AS mutual_followers_count FROM followings WHERE followerId in (SELECT followerId FROM followings WHERE userId = 6) AND followerId in (SELECT followerId FROM followings WHERE userId = 8)