2013-05-06 67 views
1

我必須與每個列(id)的表(tbla和tblb):oracle sql完全加入表中的一個不在

select * from tbla;

ID 
--- 
1 
3 
5#A 

select * from tblb; 

ID 
--- 
2 
3 

現在我需要一個完整的加盟:

select a.id, b.id 
from tbla a 
full outer join tblb b on b.id = a.id; 

ID ID1 
-------- 
1 
3 3 
5#A 
    2 

...但不包含#-sign在tbla.id

select a.id, b.id 
from tbla a 
full outer join tblb b on b.id = a.id 
where a.id not like '%#%'; 

ID ID1 
-------- 
1 
3 3 

條目,爲什麼是ID 2項從tblb失蹤?

回答

3

因爲當您執行full outer join時,任何一方的列都會以NULL的值結束。

明確檢查NULL:。

select a.id, b.id 
from tbla a 
full outer join tblb b on b.id = a.id 
where a.id not like '%#%' or a.id is null; 

(我本來建議的邏輯移動到on條款唉,full outer join保持記錄兩個表中,即使沒有記錄符合條件那麼,將條件移至on子句不能解決任何問題。)

+0

謝謝,第二選擇工作正常。第一個還包含5#A – Marc 2013-05-06 15:08:49

+0

戈登再次保存一天!謝謝! – 2013-05-06 18:03:02

0

當您執行外連接時,必須在from子句中進行篩選。如果您在where子句中執行此操作,則您的連接實際上將成爲內連接。

所以更改此設置:

full outer join tblb b on b.id = a.id 
where a.id not like '%#%' 

這個

full outer join tblb b on b.id = a.id 
and a.id not like '%#%' 
0

你是做一個完整的加盟,但在where子句中指定a.id,您篩選結果集之後。

達到你想要什麼,你可以子句移動到連接條件:

select a.id, b.id 
from tbla a 
full outer join tblb b 
    on b.id = a.id 
    and a.id not like '%#%'; 

或者你可以使用NVL:

select a.id, b.id 
from tbla a 
full outer join tblb b on b.id = a.id 
where nvl(a.id, 'n/a') not like '%#%'; 

或明確允許a.id NULL值:

select a.id, b.id 
from tbla a 
full outer join tblb b on b.id = a.id 
where (a.id is null or a.id not like '%#%');