2008-12-12 64 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