简体   繁体   中英

SQL to find mutual friends of friends

Given a User table and Friend table, for every user in user table, I want to write SQL query to find mutual friends of their friends ie For UserID in User table, find existing friends who are friends of each other. For example

user_table
userID
1
2
5

friend_table
user1    user2
1        3   
1        4
3        4
5        3
5        6

I want to be able to get:

user friend1 friend2 
1    3       4 

I tried something like this to get userID and their friends: (added UNION just to eliminate duplicates as a result of bidirectional relationships )

with ftable as (
    select user1,user2 from friend_table
),
user_friend as (
    select distinct userID, friend
    from (
        select u.userID, ft.user2 AS friend
        from user_table u JOIN ftable ft ON u.userID = ft.user1

        UNION 

        select u.userID, ft.user1 AS friend
        from user_table u JOIN ftable ft ON u.userID = ft.user2
    ) a
)



UserID  friends
1        3   
1        4
5        3
5        6

How to find existing friends who are friends of each other ?

You can just check the friends to see if they have the common friend you care about. Assuming the relationships are bi-directional:

with friends as (
      select f.user
      from friend_table ft
      where ft.user1 = @user  -- the original friend
     )
select *
from friend_table ft join 
     friends f1
     on ft.user1 = f1.user join
     friends f2
     on ft.user2 = f2.user
where ft.user1 < ft.user2   -- eliminate duplicates;

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