我想使用完整的外連接來連接兩個包含記錄(id,value)的表。這兩個表在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士丹利另一種解決方案(mofidied)
SELECT Id, Value \
FROM S1 \
UNION ALL \
SELECT Id, Value \
FROM S2 \
ORDER BY ID ASC
謝謝!
你仍然需要去說你參加什麼。例如。 'ON s1.id = s2.id'。這只是一個不需要ON的交叉連接。 – GarethD
仍然需要on子句...將「on 1 = 1」添加到查詢的結尾處,爲此功能創建一個交叉連接 – Twelfth
謝謝!這有效,但現在我有一個格式問題...任何幫助表示讚賞! – Dmitry