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       |
    ---------------------------

ケース 2:

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       |
    ---------------------------

左と右の結合クエリですべてを結合しようとしましたが、結果セットが 2 倍になります。この期待される出力を得る方法はありますか。

ありがとう、エセン。

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 に答える