我需要完全連接兩個表有多個按鍵全部加入,並加入兩個表有多個按鍵
舉個例子,我有兩個表,一個是這樣的:
id1 | foreignerkey | name | value
1 5 name1 1
2 6 name2 2
3 7 name4 3
爲t01
;另一個看起來像:
id2 | foreignerkey | name | value
1 5 name1 1
2 7 name2 2
3 8 name2 3
as t02
。
我需要「select t01.* , to2.* from t01 full join t02 on t01.name = t02.name
」, 但我也需要「select t01.* , t02.* from t01 join t02 where t01.foreignerkey = t02.foreignerkey
」,我需要的結果是這樣的:
id1 | foreignerkey | name | value | id2 | foreignerkey | name | value
1 5 name1 1 1 5 name1 1
2 6 name2 2 null null null null
3 7 name4 3 null null null null
null null null null 2 7 name2 2
null null null null 3 8 name2 3
的問題是,你可以看到,首先,我把我的查詢這樣的字符串, 「select t01.* , t02.* from t01 full join t02 on t01.name = t02.name where t01.foreignerkey = t02.foreignerkey
」,但是當t01.name = "name4"
(它不在t02
中)時,它不會顯示在結果中。
所以,我最後的查詢字符串:
select a.* from
(select t01.id1, t01.foreignerkey as foreignerkey1, t01.name, t01.value,
t02.id2, t02.foreignerkey as foreignerkey2, t02.name, t02.value
from t01
full join t02
on t01.name = t02.name) a
where a.foreignerkey1 = a.foreignerkey2
or a.foreignerkey1 is null
or a.foreignerkey2 is null
它的費用太多,得到的結果,有沒有更好的解決辦法?
返回結果「這花費太多以獲得結果「 - 你能更具體嗎? – Paolo