2008-12-12 8 views
14

ich ein Problem habe mit einer Abfrage in Oracle zu schaffen, dieOrakel links Outer-Joins nicht richtig null zeigt Werte

der Tabelle Ich habe dies auf fehlende Werte zu verbinden scheinen zu wollen, tut:

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 

ein Abbau der Felder, nachdem ich bin, ist dies:

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) 

das Ergebnis der Abfrage i bin nach ist dies:

a.refnum, b.refnum, c.refnum 

Ich dachte, das würde funktionieren:

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 

so sollten die Werte sein:

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

aber seine einzige Rückkehr:

2, 4, 7 
3, 5, 8 

i links Gedanke schließt sich alle zeigen würde Werte auf der linken Seite und erstellen Sie eine Null für die rechte Seite.

Hilfe :(

Antwort

24

Sie sind richtig, dass links sagen verbindet wird nulls für das Recht zurück, wo es keine Übereinstimmung gibt, aber sie erlauben nicht, dass diese Nullen zurückgegeben werden, wenn Sie diese Beschränkung auf Ihre where-Klausel hinzufügen :

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

Sie sollten diese setzen in der 'on' -Klausel des join statt, so dass nur relevante Reihen auf der rechten Seite zurückgegeben werden können

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

. Oder die Oracle-Syntax anstelle von Ansi verwenden

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