2008-12-12 63 views
14

我遇到了在Oracle中創建一個查詢其犯規的問題似乎想加入失蹤值甲骨文左外連接沒有顯示正確的NULL值

表我已經是這樣的:

table myTable(refnum, contid, type) 

values are: 
1, 10, 90000 
2, 20, 90000 
3, 30, 90000 
4, 20, 10000 
5, 30, 10000 
6, 10, 20000 
7, 20, 20000 
8, 30, 20000 

休息後,我是場下是這樣的:

select a.refnum from myTable a where type = 90000 
select b.refnum from myTable b where type = 10000 and contid in (select contid from myTable where type = 90000) 
select c.refnum from myTable c where type = 20000 and contid in (select contid from myTable where type = 90000) 

查詢後,我敢的結果是這樣的:

a.refnum, b.refnum, c.refnum 

我認爲這會工作:

select a.refnum, b.refnum, c.refnum 
from myTable a 
left outer join myTable b on (a.contid = b.contid) 
left outer join myTable c on (a.contid = c.contid) 
where a.id_tp_cd = 90000 
and b.id_tp_cd = 10000 
and c.id_tp_cd = 20000 

因此它們的值應該是:

1, null, 6 
2, 4, 7 
3, 5, 8 

,但其唯一的返回:

2, 4, 7 
3, 5, 8 

我想離開加入會顯示所有值在左側,併爲右側創建一個空值。

幫助:(

回答

24

你是說,左正確的連接將返回空值對於存在不匹配的權利,但你是不是讓你當這個限制添加到您的where子句中返回這些零點:

and b.id_tp_cd = 10000 
and c.id_tp_cd = 20000 

你應該能夠把這些在「上」的聯接,而不是,返回右側所以只有相關行的條款

select a.refnum, b.refnum, c.refnum 
from myTable a 
left outer join myTable b on (a.contid = b.contid and b.id_tp_cd = 10000) 
left outer join myTable c on (a.contid = c.contid and c.id_tp_cd = 20000) 
where a.id_tp_cd = 90000 
2

。或者使用Oracle語法代替ansi

select a.refnum, b.refnum, c.refnum 
from myTable a, mytable b, mytable c 
where a.contid=b.contid(+) 
and a.contid=c.contid(+) 
and a.type = 90000 
and b.type(+) = 10000 
and c.type(+) = 20000; 


REFNUM  REFNUM  REFNUM 
---------- ---------- ---------- 
    1      6 
    2   4   7 
    3   5   8