3

请参考以下脚本

    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)

情况1:

select * from @table1 a left outer join @table2 b on a.col1=b.col2
    order by col1 

结果1:

         col1       col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    5       |    NULL    |
    |    7       |    7       |
    ---------------------------

案例二:

select * from @table1 a right outer join @table2 b on a.col1=b.col2
    order by col2 

结果 2:

         col1             col2        
     -----------  ----------- 
    |    1       |    1       |
    |    3       |    3       |
    |    3       |    3       |
    |    NULL    |    4       |
    |    NULL    |    6       |
    |    7       |    7       |
    ---------------------------

实际案例:

select * from @table1 a full outer join @table2 b on a.col1=b.col2

实际结果:

         col1        col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    5       |    NULL    |
    |    7       |    7       |
    |    NULL    |    6       |
    |    NULL    |    4       |
    ---------------------------

预期结果:

         col1        col2        
     -----------  ----------- 
    |    1       |    1       |
    |    2       |    NULL    |
    |    3       |    3       |
    |    3       |    3       |
    |    NULL    |    4       |
    |    5       |    NULL    |
    |    NULL    |    6       |
    |    7       |    7       |
    ---------------------------

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

谢谢,埃森。

4

1 回答 1

5

您可以使用

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

获得您想要的订单。没有ORDER BY任何订购保证。

于 2012-11-01T19:19:42.263 回答