问题
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 IN
to 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