When or why would you use a right outer join instead of left?

后端 未结 11 649
小蘑菇
小蘑菇 2020-11-27 05:47

Wikipedia states:

\"In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins and provide no additional functi

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 06:21

    I've never used right join before and never thought I could actually need it, and it seems a bit unnatural. But after I thought about it, it could be really useful in the situation, when you need to outer join one table with intersection of many tables, so you have tables like this:

    enter image description here

    And want to get result like this:

    enter image description here

    Or, in SQL (MS SQL Server):

    declare @temp_a table (id int)
    declare @temp_b table (id int)
    declare @temp_c table (id int)
    declare @temp_d table (id int)
    
    insert into @temp_a
    select 1 union all
    select 2 union all
    select 3 union all
    select 4
    
    insert into @temp_b
    select 2 union all
    select 3 union all
    select 5
    
    insert into @temp_c
    select 1 union all
    select 2 union all
    select 4
    
    insert into @temp_d
    select id from @temp_a
    union
    select id from @temp_b
    union
    select id from @temp_c
    
    select *
    from @temp_a as a
        inner join @temp_b as b on b.id = a.id
        inner join @temp_c as c on c.id = a.id
        right outer join @temp_d as d on d.id = a.id
    
    id          id          id          id
    ----------- ----------- ----------- -----------
    NULL        NULL        NULL        1
    2           2           2           2
    NULL        NULL        NULL        3
    NULL        NULL        NULL        4
    NULL        NULL        NULL        5
    

    So if you switch to the left join, results will not be the same.

    select *
    from @temp_d as d
        left outer join @temp_a as a on a.id = d.id
        left outer join @temp_b as b on b.id = d.id
        left outer join @temp_c as c on c.id = d.id
    
    id          id          id          id
    ----------- ----------- ----------- -----------
    1           1           NULL        1
    2           2           2           2
    3           3           3           NULL
    4           4           NULL        4
    5           NULL        5           NULL
    

    The only way to do this without the right join is to use common table expression or subquery

    select *
    from @temp_d as d
        left outer join (
            select *
            from @temp_a as a
                inner join @temp_b as b on b.id = a.id
                inner join @temp_c as c on c.id = a.id
        ) as q on ...
    

提交回复
热议问题