Lior Lior - 4 months ago 7
SQL Question

Multiple sql joins same table

I have this query:

SELECT b.id, b.date, members.username, b.type, b.amount, FROM b LEFT JOIN members ON b.user_id = members.id WHERE a.something = 1


Now I want to select another
members.username
, but now I want it to be by the
b.other_user_id
.

How can I achieve that?

vkp vkp
Answer

Join the members table with a different alias on the required condition and select the required column from that table.

SELECT b.id, b.date, m1.username, b.type, b.amount, m2.username
FROM b 
LEFT JOIN members m1 ON b.user_id = m1.id AND a.something = 1
LEFT JOIN members m2 ON b.other_user_id = m2.id 
Comments