1

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

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
nikola
  • 117
  • 6

4 Answers4

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
MTwem
  • 135
  • 1
  • 1
  • 9
0

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.

Alan Lacerda
  • 758
  • 1
  • 6
  • 12
0

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
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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:

SOLUTION 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:

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)

freeguy
  • 11
  • 5