0

I have two tables representing users and their friends: users and friendships

  • users has id and name
  • friendships has id, friend1_id and friend2_id

By searching a user's name, I want to get their associated friends' names.

2
  • did you test the answer that you accepted? Check this: db-fiddle.com/f/oD5vzNH9H7tXQMR4HJDint/2 it does not return your expected results. Commented Jun 10, 2020 at 18:57
  • @forpas it works as expected. The relationships are one way. Commented Jun 11, 2020 at 12:14

2 Answers 2

1

You can try this:

SELECT u2.name from users u1
INNER JOIN users u2 ON u1.name = [your_name_to_search]
INNER JOIN friendships fs 
ON u2.id = fs.friend2_id AND u1.id = fs.friend1_id

Explanation:

I used 2 joins in this approach: the first users self join will assure you take the id corresponding to [your_name_to_search], and then the second join with friendships will extract the names of friend_2_id matching with the friend_1_id taken from the first join.

You can test this approach on this db-fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Join friendships to 2 copies of users.
The 1st copy will be filtered for the user name that you search for and the 2nd will return all the user's friends:

select uf.name
from users u
inner join friendships fs on u.id in (fs.friend1_id, fs.friend2_id)
inner join users uf on uf.id in (fs.friend1_id, fs.friend2_id) and uf.id <> u.id
where u.name = ?

Replace ? with the name of the user whose friends you want in the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.