简体   繁体   中英

Oracle join 2 tables on same column

Can someone explain to me why the below query is returning null in the description field

Table A:

OCD CCD 
A   B
C   D
E   F

Table B:
CD   DESCRIP
A    AL
B    BL
C    CL
D    DL
E    EL
F    FL

Result:
OCD  DESCRIP CCD DESCRIP
A    AL      B   BL
C    CL      D   DL
E    EL      F   FL

Incorrect Query:although this query runs correctly. It doesn't give description values.

select a.ocd,b.DESCRIP,a.CCD,b.DESCRIP
from A a, B b
where a.ocd=b.cd(+)
and a.ccd=b.cd(+);

Correct query

select a.ocd,b.DESCRIP,a.CCD,b.DESCRIP
from A a, B b1, B b2
where a.ocd=b1.cd(+)
and a.ccd=b2.cd(+);

You need to look up the values twice because you have two codes. This requires two joins, which should be left join s if there is a possibility of non-matches:

select a.ocd, b1.DESCRIP, a.CCD, b2.DESCRIP
from A left join
     B b1
     on a.ocd = b1.cd left join
     B b2
     on a.ccd = b2.cd;

The conditions in your first query are:

where a.ocd=b.cd(+) and a.ccd=b.cd(+);

Just look at them. They imply that in any matching row, a.ocd = a.ccd , and that is not true on any rows in your data. Hence, there is no match and the result is NULL .

Also, learn to use proper explicit JOIN syntax. Explicit joins are more powerful, more portable, and easier to read. Further, Oracle deprecated the (+) syntax many years ago, meaning that even Oracle may not support it in the future.

From what you call the "correct query" it seems you want to select each row from table A, and then for each value in that row, the corresponding value in a row in Table B. In the first query, where you join table A and table B, the join condition requires that both values from the row in table A are matched IN THE SAME ROW in table B. Clearly that doesn't meet your specification. If you want to match one row from table A with two (usually DIFFERENT) rows from table B, you need to join table A with table B twice, as in the correct query.

When you join two tables, all the combinations of ONE ROW from the first table and ONE ROW from the second table are checked to see if the join condition(s) is/are met. When you join three tables, all the combinations of ONE ROW from each of the three tables are checked against the join condition(s). This is why you need table B twice in your join: you want to combine one row from table A and TWO rows from table B for one row in the result.

You should translate your query to standard SQL:

select a.ocd, b.DESCRIPT, a.CCD, b.DESCRIPT
from a
left join b on a.ocd = b.cd and a.ccd = b.cd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM