合并两个表的SQL语法?

发布于 2024-11-08 07:40:19 字数 368 浏览 0 评论 0原文

我有两个表想合并如下。

表 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

I have two tables I would like to merge as follows.

Table a:

columns :a1     a2
data    :aaa    a2
         bbb    b2

Table b:

columns :a1     b2
data    :aaa    a3
         ccc    c3

The final desired output table would include the following:

Table final:

columns :a1     a2    b2
data    :aaa    a2    a3
         bbb    b2
         ccc          c3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夜无邪 2024-11-15 07:40:19
SELECT
       a.a1, a.a2, b.b2
FROM 
       a 
FULL JOIN 
       b ON a.a1 = b.a1
SELECT
       a.a1, a.a2, b.b2
FROM 
       a 
FULL JOIN 
       b ON a.a1 = b.a1
鸩远一方 2024-11-15 07:40:19
-- 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
-- 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

Result:

a1   a2   b2
---- ---- ----
aaa  a1   a3
ccc  NULL c3
bbb  b2   NULL
沙沙粒小 2024-11-15 07:40:19

您需要使用类似的内容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 上运行。

You need toJOIN the two tables with something like

SELECT a.a1, a.a2, b.b2 FROM table_a a 
JOIN table_b b ON a.a1 = b.a1

Depending on what you need, you may need a lEFT JOIN (sometimes called an OUTER JOIN). The actual syntax also depends on what database you are using. This example will work on MySQL.

拍不死你 2024-11-15 07:40:19
SELECT a.a1, a.a2, b.b2
INTO NewTable
FROM a,b
Where b.a1=a.a1
SELECT a.a1, a.a2, b.b2
INTO NewTable
FROM a,b
Where b.a1=a.a1
丶情人眼里出诗心の 2024-11-15 07:40:19

这应该是您正在寻找的内容:

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

This should be what you are looking for:

SELECT
       ISNULL(a.a1, b.a1) AS a1, a.a2, b.b2
FROM 
       a 
FULL OUTER JOIN 
       b ON a.a1 = b.a1

For more info on Outer Joins in general see:
http://msdn.microsoft.com/en-us/library/ms187518.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文