Albert Hendriks
Albert Hendriks

Reputation: 2145

nesting joins right to left in postgres

I have a big query, but it all boils down to this:

SELECT * FROM user
LEFT JOIN tableA ON tableA.user_id = user.id
JOIN tableB ON tableB.a_id = tableA.id

Now, I get too few results. If the combination of user with (tableA x tableB) does not exist, I still want the user. So with syntax error, what I want is something like this:

SELECT * FROM user
LEFT JOIN (tableA ON tableA.user_id = user.id
           JOIN tableB ON tableB.a_id = tableA.id)

is that possible, perhaps without RIGHT JOINS?

Of course, I don't want to change the second JOIN to LEFT JOIN, because that would give too many results.

Upvotes: 0

Views: 52

Answers (1)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

You can try this:

SELECT * FROM user
LEFT JOIN (SELECT * FROM tableA
           JOIN tableB ON tableB.a_id = tableA.id) t
ON t.user_id = user.id

You will need to select distinct columns in subquery here if any exists.

Upvotes: 1

Related Questions