MySQL inner join with 2 columns
I have one table users with 2 fields : id , name and another table friends with 2 fields : userid1 userid2 .
So this means userid1 is friend with userid2 . I want , with one inner or left join to show this :
userid1 name(got from users table) is friend with userid2 name(got from users table)
something
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id AND friends.userid2 = users.id but this is not working.
Any good query with good explanation please?
If, for example I have the next details in the users table : ID : 1 NAME : FinalDestiny ID : 2 NAME : George
and the next details in the friends table : ID1 : 1 ID2 : 2
So this means 1 is friend with 2.
I need with one query to get t开发者_运维百科he name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George
I know that you specify that you want this done with one join, but it looks to me like you need two. I believe this query will give you what you need:
SELECT u1.Name, u2.Name
FROM Users u1, Users u2, Friends f
WHERE u1.id = f.userid1 AND u2.id = f.userid2
I am joining the Users table with the Friends table with on Users.id = Friends.userid1. Then, I am joining this new table with the Users table on (new table).userid2 = Users.id. This results in a table with 4 columns. These columns are the original 2 columns of the Friends table in addition to 2 columns for the names of the friends. u1
, u2
, and f
and referring to the three tables that were joined. The users table was joined with the friends table twice. u1
is the copy of the Users table that was joined on Friends.userid1 = User.id. u2
is the copy of the Users table that was joined on Friends.userid2 = User.id.
From this table with 4 columns, I am selecting only the names of the friends.
Let me know if more explanation is needed.
You check on a user being a friend of itself. Use OR
in your select to match user's friends:
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id OR friends.userid2 = users.id
If, for example I have the next details in the users table : ID : 1 NAME : FinalDestiny ID : 2 NAME : George
and the next details in the friends table : ID1 : 1 ID2 : 2
So this means 1 is friend with 2.
I need with one query to get the name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George
精彩评论