sql合并两个表,其中公共字段不完整

时间:2012-12-20 08:31:09

标签: sql sql-server sql-server-2008 join merge

在SQL Server 2008中,我有以下两个表

  Table_1:
C1  C2
A   TypeStringA-1
B   TypeStringA-2
C   TypeStringA-3
D   TypeStringA-4
E   TypeStringA-5

  Table_2
C1  C2
A   TypeStringB-1
B   TypeStringB-2
D   TypeStringB-3
E   TypeStringB-4

我想展示以下数据:

  Result
A  TypeStringA-1 TypeStringB-1
B  TypeStringA-2 TypeStringB-2
C  TypeStringA-3 Null
D  TypeStringA-4 TypeStringB-3
E  TypeStringA-5 TypeStringB-4

现在我所拥有的是两个子查询和一个位置:

select
query1.C1
query1.C2
query2.C2
(select C1, C2 
from Table_1) as query1
(select C2
from table_2) as query2
where query1.C1 = query2.C1
order by query1.C1

然而,在我的结果中逻辑上,我没有我需要显示的Null数据,这就是我得到的:

  Result
A  TypeStringA-1 TypeStringB-1
B  TypeStringA-2 TypeStringB-2
D  TypeStringA-4 TypeStringB-3
E  TypeStringA-5 TypeStringB-4

问题是我应该使用Null数据来拍摄表格。

1 个答案:

答案 0 :(得分:2)

select  coalesce(t1.C1, t2.C1)
,       t1.C2
,       t2.C2
from    Table_1 t1
full outer join
        Table2 t2
on      t1.C1 = t2.C1