I have three tables: R, S and P.
Table R Joins with S through a foreign key; there should be at least one record in S, so I can JOIN:
SELECT
*
FROM
R
JOIN S ON (S.id = R.fks)
If there’s no record in S then I get no rows, that’s fine.
Then table S joins with P, where records is P may or may not be present and joined with S.
So I do
SELECT
*
FROM
R
JOIN S ON (S.id = R.fks)
LEFT JOIN P ON (P.id = S.fkp)
What if I wanted the second JOIN to be tied to S not to R, like if I could use parentheses:
SELECT
*
FROM
R
JOIN (S ON (S.id = R.fks) JOIN P ON (P.id = S.fkp))
Or is that already a natural behaviour of the cartesian product between R, S and P?
All kinds of outer and normal joins are in the same precedence class and operators take effect left-to-right at a given nesting level of the query. You can put the join expression on the right side in parentheses to cause it to take effect first. Remember that you will have to move the
ONclauses around so that they stay with their joins—the join in parentheses takes itsONclause with it into the parentheses, so it now comes textually before the otherONclause which will be after the parentheses in the outer join statement.(PostgreSQL example)
In
the a-b join takes effect first, but we can force the b-c join to take effect first by putting it in parentheses, which looks like:
Often you can express the same thing without extra parentheses by moving the joins around and changing the direction of the outer joins, e.g.