2011-10-31 93 views
0

我需要完全連接兩個表有多個按鍵全部加入,並加入兩個表有多個按鍵

舉個例子,我有兩個表,一個是這樣的:

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 

它的費用太多,得到的結果,有沒有更好的解決辦法?

+0

返回結果「這花費太多以獲得結果「 - 你能更具體嗎? – Paolo

回答

0

我不能確認這是快如你原來的SQL不上的Oracle版本,但工作,我用你可以試試這個:

SELECT * 
    FROM t01, t02 
WHERE t01.NAME = t02.NAME 
    AND t01.foreignerkey = t02.foreignerkey 
UNION ALL 
SELECT t01.*, NULL, NULL, '', '' 
    FROM t01 
WHERE NOT EXISTS (SELECT NULL 
      FROM t02 
     WHERE t01.NAME = t02.NAME 
      AND t01.foreignerkey = t02.foreignerkey) 
UNION ALL 
SELECT NULL, NULL, '', '', t02.* 
    FROM t02 
WHERE NOT EXISTS (SELECT NULL 
      FROM t01 
     WHERE t01.NAME = t02.NAME 
      AND t01.foreignerkey = t02.foreignerkey) 
  • 使用一個內連接到t01.NAME = t02.NAME AND t01.foreignerkey = t02.foreignerkey
  • 使用NOT EXISTS從T01得到記載,不要在T01比賽
  • 使用NOT EXISTS擺脫T02是不要在T01比賽
  • 使用UNION加入結果集在這種情況下,記錄的所有是安全的,因爲我們知道,這三個結果集互斥

或者你可以使用一個外部聯接爲@kedar kamthe已經sugested:

SELECT * 
    FROM t01, t02 
WHERE t01.NAME = t02.NAME(+) 
    AND t01.foreignerkey = t02.foreignerkey(+) 
UNION 
SELECT NULL, NULL, '', '', t02.* 
    FROM t02 
WHERE NOT EXISTS (SELECT NULL FROM t01 WHERE t01.NAME = t02.NAME AND t01.foreignerkey = t02.foreignerkey) 

但你仍然需要第二個查詢從T02

+0

非常鼓舞人心,謝謝。 – user1021531

0

,你可以簡單地使用在這種情況下,「外連接」上foreignerkey列。

1

我不明白爲什麼你需要的內部查詢

select t01.id1,t01.foreignerkey as foreignerkey1,t01.name,t01.value, 
    t02.id2,t02.foreignerkey as foreignerkey2,t02.name,t02.value 
from t01 
full outer join t02 on a.foreignerkey1=a.foreignerkey2 AND t01.name = t02.name