When to open and close brackets surrounding joins in MS Access SQL

前端 未结 1 2020
小蘑菇
小蘑菇 2020-12-04 00:25

I want to understand when to open and close brackets when representing joins in MS Access queries as I am developing a query builder using C++ for MS Access queries so that

相关标签:
1条回答
  • 2020-12-04 01:12

    Essentially, when an MS Access query references more than two tables, every successive join between a pair of tables should be nested within parentheses.

    For example, a query with two tables requires no parentheses:

    select *
    from a inner join b on a.id = b.id
    

    The addition of a third joined table necessitates parentheses surrounding the original join in order to distinguish it from the additional join:

    select *
    from 
    (
        a inner join b on a.id = b.id
    ) 
    inner join c on a.id = c.id
    

    Every successive addition of a table will then cause the existing joins to be nested within another level of parentheses:

    select *
    from 
    (
        (
            a inner join b on a.id = b.id
        ) 
        inner join c on a.id = c.id
    )
    inner join d on a.id = d.id
    

    Hence, in general:

    select *
    from 
    (
        (
            (
                (
                    table1 [inner/left/right] join table2 on [conditions]
                ) 
                [inner/left/right] join table3 on [conditions]
            )
            [inner/left/right] join table4 on [conditions]
        )
        ...
    )
    [inner/left/right] join tableN on [conditions]
    

    There is a subtlety where LEFT/RIGHT joins are concerned, in that the order of nesting must maintain the direction of the join, for example:

    select *
    from 
    (
        c left join b on c.id = b.id
    ) 
    left join a on a.id = b.id
    

    Could be permuted to:

    select *
    from 
    c left join
    (
        b left join a on b.id = a.id
    )
    on c.id = b.id
    
    0 讨论(0)
提交回复
热议问题