我想使用完全外连接来连接两个带有记录(id、值)的表。这两个表在 id 字段上没有交集,但我想通过 id 字段加入它们。我正在尝试使用完全外部联接来完成此联接,但我不明白如何。
我正在使用 DB2。
到目前为止,我有(每个语句单独手动执行):
create table S1 (
id integer primary key not null,
value integer not null)
create table S2 (
id integer primary key not null,
value integer not null)
insert into S1 values (0, 50)
insert into S1 values (1, 20)
insert into S2 values (2, 40)
insert into S2 values (3, 90)
select * from S1 full outer join S2
我在完整的外部连接尝试中收到错误:
SQL0104N An unexpected token "join S2" was found following "* from S1 full
outer". Expected tokens may include: "<space>". SQLSTATE=42601
编辑:谢谢!我得到了它的工作,但这不是我所期望的。
select * from S1 full outer join S2 on S1.id = S2.id
问题是现在它显示(:表示空间)
+--+-----+--+-----+
|ID|VALUE|ID|VALUE|
+--+-----+--+-----+
|-:|-::::|3:|90:::|
+--+-----+--+-----+
|-:|-::::|2:|40:::|
+--+-----+--+-----+
|1:|20:::|-:|-::::|
+--+-----+--+-----+
|0:|50:::|-:|-::::|
+--+-----+--+-----+
我不想要重复的字段。有没有办法让表连接成:
+--+-----+
|ID|VALUE|
+--+-----+
桌子?
我尝试使用
select id from s1
full outer join s2 on s1.id = s2.id
不用说,我得到
SQL0203N A reference to column "ID" is ambiguous. SQLSTATE=42702
解决了!
select coalesce(s1.id, s2.id) as id, \
coalesce (s1.value, s2.value) as value \
from s1 full outer join s2 on s1.id = s2.id and s1.value = s2.value
group by id asc
以及 D Stanley 的另一个解决方案(已修改)
SELECT Id, Value \
FROM S1 \
UNION ALL \
SELECT Id, Value \
FROM S2 \
ORDER BY ID ASC
谢谢!