SQL Friends List Query

允我心安 提交于 2020-07-16 05:39:12

问题


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 be friends with each other. For that I created the friends table where it has a user_id and friend_user_id. So let's say we have (1,2), (2,3). I want this to be read as: "2 is friends with 1 and 3, 1 is friends with 2, 3 is friends with 2". So when inserting on this friends table I never do something like this (1,2),(2,1). I'm looking for a procedure that by receiving an user_id as parameter to return all his friends whether they are in the user_id column or the friend_user_id column. For example, if I look for user 2's friends it should appear 1 column with 1 and 3, because 1 and 3 are friends with 2.

To be more specific, when I call get_friends(2) it should appear

[1]
[3]

Even though these are in different columns on the friends table.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/50898531/sql-friends-list-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!