[英]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.