Reputation: 1646
Say I have users and that users can be friends. I have a table of users and user data, and a table of friendships (connection id, user a id, user b id).
Is there a single query I could do in mySQL that would grab all of the users from the users table that are friends with user x? The fact that user x's id could be in either the a slot or the b slot in the friendships table makes this more complicated than I can figure out.
Edit For Clarity:
I need all of the data in the users table for friends of the current user. So I need the user data for user b if the current user is user a in the friendships table and vice versa. I want to end up with all of the data for all of the current user's friends (from the users table) based on the relationship in the friendship table.
Upvotes: 0
Views: 77
Reputation: 5407
Using SQL Fiddle you can do:
SELECT u.name as friends
FROM friendship AS f
JOIN users AS u ON
((u.user_id = f.user_a_id AND f.user_b_id = @user_id)
or (u.user_id = f.user_b_id AND f.user_a_id = @user_id))
where u.user_id is not null;
In this @user_id
is the id number of the user you want to find the friends for and the output are the names of the friends.
Upvotes: 4
Reputation: 2669
SELECT users.user_id FROM users, friends WHERE (users.user_id=friends.user_a_id AND friends.user_b_id=x) OR (users.user_id=friends.user_b_id AND friends.user_a_id=x);
Upvotes: 0