Mutual friends sql with join (Mysql)

前端 未结 4 1031
情书的邮戳
情书的邮戳 2020-12-06 03:41

I have two tables

users table:

id|name

user_relationships

id | user_id | friend_id

and want to ge

相关标签:
4条回答
  • 2020-12-06 04:18

    You need to join user_relationships with itself, so that two rows with different user_id have the same friend_id

    All mutual friends:

    select ur1.user_id user1, 
           ur2.user_id user2, 
           ur2.friend_id mutual_friend
    from   user_relationships ur1 
           JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
    where  ur1.user_id != ur2.user_id
    

    Join with users table to get the names:

    select ur1.user_id user_id1, 
            u1.name User1, 
           ur2.user_id user2, 
            u2.name User2,
           ur2.friend_id mutual_friend_id,
            u3.name mutual_friend
    from user_relationships ur1 
         JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
         JOIN user u1 ON u1.user_id = ur1.user_id
         JOIN user u2 ON u1.user_id = ur2.user_id
         JOIN user u3 ON ur1.user_id = u3.user_id
    where ur1.user_id != ur2.user_id
    

    You can filter for mutual friends for some specific users using ur1.user_id = first_user and ur2.user_id = second_user

    0 讨论(0)
  • 2020-12-06 04:25

    didn't check it but this query should give you a list of related user names for ID [no].

    select u1.name, u2.name 
      from users as u1
      join user_relationships as ur
        on u1.id = ur.user_id
      join users as u2
        on ur.friend_id = u2.id
      where U1.id = [no];
    

    BTW, you don't need an artificial id for your cross-table, as (user_id, friend_id) is already a legitimate primary key.

    0 讨论(0)
  • 2020-12-06 04:26
    SELECT id, name
    FROM users
    WHERE id IN (
      SELECT friend_id
      FROM user_relationships
      WHERE user_id IN ( 1, 2 )
      GROUP BY friend_id
      HAVING COUNT(friend_id) >= 2
    )
    

    or with one join:

    SELECT friend_id, name
    FROM user_relationships r
      INNER JOIN users u ON r.friend_id = u.id
    WHERE user_id IN ( 1, 2 )
    GROUP BY friend_id
    HAVING COUNT(friend_id) >= 2
    
    0 讨论(0)
  • 2020-12-06 04:34

    You could try something like this:

    select id, name from users where id in 
        (select friend_id from user_relationships where user_id = @user1_id and friend_id in 
            (select friend_id from user_relationships where user_id = @user2_id)
        )
    

    This should return all mutual friends of users with the IDs @user1_id and @user2_id. It's not tested yet, but should provide a starting point...

    0 讨论(0)
提交回复
热议问题