我正在尝试堆叠我在sql中匹配的列对。例如,我匹配来自不同表的列A到列B中的条目,然后我想将列C和D添加到列A和B.它应该如下所示:
A1 B1
A2 B2
C1 D1
C2 D2
有一种简单的方法吗?我可以将ABCD列添加到表中,但是我对sql语法的了解不足以将其插入到另一个表中。插入到语句中看起来很有希望,这里有一些我试过的代码根本不起作用:
SELECT
col_A,
col_B
FROM
table_A as a
LEFT JOIN
table_B as b on b.ID = a.ID;
--this is where I think I'm messing up:
INSERT INTO a
col_C,
col_D
FROM
table_c as c
LEFT JOIN
table_d as d on d.ID = c.ID
有什么想法吗?更简单的方法吗?谢谢! (如果改变了什么,我需要使用PostgreSQL)
答案 0 :(得分:0)
假设您尝试追加的数据属于同一类型,则可以使用union all(如果要删除重复项,则使用union):
WITH table1 AS (
SELECT
col_A,
col_B
FROM table_A as a
LEFT JOIN table_B as b
on b.ID = a.ID
),
table2 AS (
SELECT
col_C,
col_D
FROM table_C as c
LEFT JOIN table_D as d
on c.ID = d.ID
)
SELECT *
FROM table1
union all
SELECT *
FROM table2
;