简体   繁体   中英

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

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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