SQL Friends List Query

前端 未结 2 1063
难免孤独
难免孤独 2021-01-22 00:56

I am new to this database SQL language so I will try to make it as simple as possible. (I am using MySQL Workbench)

I have a table for User and I want multiple users to

相关标签:
2条回答
  • 2021-01-22 01:09

    You can use INto check if either column is equal to the ID of the user you want to look up and a CASE ... END to take the column which is not equal to the ID of the user you want to look up.

    SELECT CASE
             WHEN user_id = 2
               THEN user_friend_id
             WHEN user_friend_id = 2
               THEN user_id
           END friend
           FROM friends
           WHERE 2 IN (user_id, user_friend_id);
    

    Alternatively you could use a UNION ALL approach, which might perform better as it can use indexes on user_id or user_friend_id.

    SELECT user_id friend
           FROM friends
           WHERE user_friend_id = 2
    UNION ALL
    SELECT user_friend_id friend
           FROM friends
           WHERE friend_id = 2;
    

    But this is only better if there are such indexes. If there aren't, it will need two scans on the table opposed to the first approach only needing one. So it's worse in that case.

    0 讨论(0)
  • 2021-01-22 01:34

    Use UNION ALL to get all friends, parameterize this query:

    select friend_user_id as friend_id from friends f where f.user_id = 2 --parameter
    union all
    select user_id as friend_id from friends f where f.friend_user_id = 2 --parameter
    
    0 讨论(0)
提交回复
热议问题