Benjamin Crouzier
Benjamin Crouzier

Reputation: 41895

Mysql, double join that use the same table twice, but indirectly

There are plenty of question about join on the same table, but I can't find something related to my problem

I have two tables:

user (id, name)
friends (from, to)

And I have the following query. It is supposed to retrieve all users with their friends :

SELECT user.id, user.name, f.to, friend.id, friend.name
FROM user

LEFT JOIN friends f ON user.id = f.from
LEFT JOIN user friend ON  user.id = f.to
LIMIT 0, 200

It returns something like this:

id name from to id   name
1  bob  1    3  NULL NULL
1  bob  1    4  NULL NULL
2  toto 2    7  NULL NULL

The from and two are correct, but the second join doesn't seem to work. Do you have any ideas what is wrong with the second join ?

Upvotes: 1

Views: 693

Answers (1)

Sjoerd
Sjoerd

Reputation: 75609

Try this:

SELECT user.id, user.name, f.to, friend.id, friend.name
FROM user
LEFT JOIN friends f ON user.id = f.from
LEFT JOIN user friend ON friend.id = f.to
LIMIT 0, 200

Note that I replaced user with friend in the join condition.

Upvotes: 3

Related Questions