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
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.
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