请参阅以下脚本
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 |
---------------------------
我尝试使用左右连接查询进行联合,但它将结果集加倍。有没有办法让我得到这个预期的输出。
谢谢, 也先。
答案 0 :(得分:4)
您可以使用
SELECT *
FROM @table1 a
FULL OUTER JOIN @table2 b
ON a.col1 = b.col2
ORDER BY Isnull(col1, col2)
获得您想要的订单。如果没有ORDER BY
,则无法保证订购。