views:

195

answers:

4

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 the name of 1 and the name of 2 and to echo that they're friends

FinalDestiny is friend with George

+1  A: 

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 
alemjerus
A: 

Please re-formulate your question, your question makes no sense to us

Muleskinner
Edited and added more details
FinalDestiny
This is not an answer - it should have been a comment.
Mark Byers
A: 

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

FinalDestiny
A: 

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.

Brett Widmeier
Whats u1.name ? Please do the query using my specifications , users table, friends table and my fields
FinalDestiny
Editing to explain.
Brett Widmeier