SQL joining three tables, join precedence

后端 未结 4 498
清酒与你
清酒与你 2020-12-14 15:53

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         


        
4条回答
  •  别那么骄傲
    2020-12-14 16:44

    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 have to move the ON clause of the join that is now outside the join you put parens on.

    (PostgreSQL example)

    In SELECT * FROM a LEFT JOIN b ON (a.id = b.id) JOIN c ON (b.ref = c.id);

    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:

    SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);

    Often you can express the same thing without extra parentheses by moving the joins around and changing the outer join direction, e.g.

    SELECT * FROM b JOIN c ON (b.ref = c.id) RIGHT JOIN a ON (a.id = b.id);

提交回复
热议问题