我有两个表,我想合并如下。
表a:
columns :a1 a2
data :aaa a2
bbb b2
表b:
columns :a1 b2
data :aaa a3
ccc c3
最终所需的输出表将包括以下内容:
决赛桌:
columns :a1 a2 b2
data :aaa a2 a3
bbb b2
ccc c3
答案 0 :(得分:3)
SELECT
a.a1, a.a2, b.b2
FROM
a
FULL JOIN
b ON a.a1 = b.a1
答案 1 :(得分:1)
-- Test data
with TableA(a1, a2) as
(
select 'aaa', 'a1' union all
select 'bbb', 'b2'
),
TableB(a1, b2) as
(
select 'aaa', 'a3' union all
select 'ccc', 'c3'
)
select
coalesce(A.a1, B.A1) as a1,
A.a2,
B.b2
from TableA as A
full outer join TableB as B
on A.a1 = B.a1
结果:
a1 a2 b2
---- ---- ----
aaa a1 a3
ccc NULL c3
bbb b2 NULL
答案 2 :(得分:0)
您需要JOIN
两个表格,如
SELECT a.a1, a.a2, b.b2 FROM table_a a
JOIN table_b b ON a.a1 = b.a1
根据您的需要,您可能需要lEFT JOIN
(有时称为OUTER JOIN
)。实际语法还取决于您使用的数据库。这个例子适用于MySQL。
答案 3 :(得分:0)
SELECT a.a1, a.a2, b.b2
INTO NewTable
FROM a,b
Where b.a1=a.a1
答案 4 :(得分:0)
这应该是你要找的东西:
SELECT
ISNULL(a.a1, b.a1) AS a1, a.a2, b.b2
FROM
a
FULL OUTER JOIN
b ON a.a1 = b.a1
有关外部联接的更多信息,请参阅: http://msdn.microsoft.com/en-us/library/ms187518.aspx