[英]Sql query to get mutual friends
我有两个表,一个称为用户(id,名字,姓氏......)第二个称为关注,其中包含有关哪个用户正在关注其他用户的数据
下表示例
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
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
有多种方法可以实现您想要的,但这应该可以解决问题:
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
您可以在此处查看一个工作示例。
从用户加入以下两个:
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
您也可以使用子查询来执行此操作。 因此,如果您想获取 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.