简体   繁体   English

Sql 查询获取共同好友

[英]Sql query to get mutual friends

I have two tables one is called users ( id,first name,last name...) second one is called followings which contains data about which user is following other users我有两个表,一个称为用户(id,名字,姓氏......)第二个称为关注,其中包含有关哪个用户正在关注其他用户的数据

Followings table example下表示例

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

How do I get number of mutual friends between two users如何获取两个用户之间的共同好友数

Expected result should be预期结果应该是

first_user second_user num_of_mutual_friends
    83          73               3
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

There are multiple ways of achieving what you want, but this should do the trick:有多种方法可以实现您想要的,但这应该可以解决问题:

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

You can check here a working example.您可以在此处查看一个工作示例。

Join from users to both followings:从用户加入以下两个:

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

You can also do this using subqueries.您也可以使用子查询来执行此操作。 So, if you want to get the number of mutual followers between user with id 8 and user with id 6, you can use this:因此,如果您想获取 id 为 8 的用户和 id 为 6 的用户之间的相互关注者数量,可以使用以下命令:

SOLUTION 1:解决方案 1:

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

SOLUTION 2:解决方案 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM