Amazon RSQL 连接具有 2 个共享列的两个表

问题描述 投票:0回答:1

我有这样一个表格的例子:

表1:

第 1 栏 col2 col3 col4
1 a x1 asdc
2 b x2 czxa
3 c x3 xfsdaa

表2:

col2 col3
l x56
q x99

我想要的就是收到这样一个最终的串联

第 1 栏 col2 col3 col4
1 a x1 asdc
2 b x2 czxa
3 c x3 xfsdaa
l x56
q x99

如何在 RSQL(基于 postgresql 的 SQL)中实现它?我考虑过从第一个表中选择所有列,然后使用

union all
并使用
NULL AS col1 [...] NULL AS col4
代替缺失的列,但在实际数据中,我有几十列,因此代码看起来不太好。

还有其他方法可以实现吗?

sql postgresql amazon-web-services concatenation amazon-redshift
1个回答
0
投票

在您想要跳过字段的地方使用

UNION
子句和
null
常量:demo

create table table1(col1, col2, col3, col4) as values
 (1,    'a',    'x1',   'asdc')
,(2,    'b',    'x2',   'czxa')
,(3,    'c',    'x3',   'xfsdaa');

create table table2(col2,col3) as values
 ('l',  'x56')
,('q',  'x99');

select col1, col2, col3, col4 from table1
union all
select null,col2,col3,null from table2;
col1 col2 col3 col4
1 a x1 asdc
2 b x2 czxa
3 c x3 xfsdaa
l x56
q x99
© www.soinside.com 2019 - 2024. All rights reserved.