如何以左右连接顺序获得完全外连接

Ese*_*sen 3 sql sql-server-2008-r2

请参考以下脚本

    declare @table1 table
    (
    col1 int
    )

    declare @table2 table
    (
    col2 int
    )

    insert into @table1 values(1)
    insert into @table1 values(2)
    insert into @table1 values(3)
    insert into @table1 values(5)
    insert into @table1 values(7)

    insert into @table2 values(1)
    insert into @table2 values(3)
    insert into @table2 values(3)
    insert into @table2 values(6)
    insert into @table2 values(4)
    insert into @table2 values(7)
Run Code Online (Sandbox Code Playgroud)

情况1:

select * from @table1 a left outer join @table2 b on a.col1=b.col2
    order by col1 
Run Code Online (Sandbox Code Playgroud)

结果 1:

         col1       col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    5       |    NULL    |
    |    7       |    7       |
    ---------------------------
Run Code Online (Sandbox Code Playgroud)

案例2:

select * from @table1 a right outer join @table2 b on a.col1=b.col2
    order by col2 
Run Code Online (Sandbox Code Playgroud)

结果 2:

         col1             col2        
     -----------  ----------- 
    |    1       |    1       |
    |    3       |    3       |
    |    3       |    3       |
    |    NULL    |    4       |
    |    NULL    |    6       |
    |    7       |    7       |
    ---------------------------
Run Code Online (Sandbox Code Playgroud)

实际案例:

select * from @table1 a full outer join @table2 b on a.col1=b.col2
Run Code Online (Sandbox Code Playgroud)

实际结果:

         col1        col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    5       |    NULL    |
    |    7       |    7       |
    |    NULL    |    6       |
    |    NULL    |    4       |
    ---------------------------
Run Code Online (Sandbox Code Playgroud)

预期结果:

         col1        col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    NULL    |    4       |
    |    5       |    NULL    |
    |    NULL    |    6       |
    |    7       |    7       |
    ---------------------------
Run Code Online (Sandbox Code Playgroud)

我尝试使用左右连接查询联合所有,但它使结果集加倍。有没有办法可以得到这个预期的输出。

谢谢,埃森。

Mar*_*ith 5

您可以使用

SELECT *
FROM   @table1 a
       FULL OUTER JOIN @table2 b
         ON a.col1 = b.col2
ORDER  BY Isnull(col1, col2) 
Run Code Online (Sandbox Code Playgroud)

以获得您想要的订单。如果没有ORDER BY没有顺序保证。