Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining 3 tables Oracle SQL

Tags:

sql

join

oracle

I have 3 tables listing below:

Table_A:

order_number | header_id
        123  | 80001

Table_B

   header_id | line_id | quantity
       80001 | 10001   | 1
       80001 | 10002   | 3
       80001 | 10003   | 5

Table_C

   header_id | line_id | hold_price_id | released_flag
       80001 |   10001 | 2001          | Y
       80001 |   10002 | 2002          | Y
       80001 |   10003 | 2003          | N

I wrote a query as shown below:

SELECT A.order_number, A.header_id, B.line_id, B.quantity, C.hold_price_id, C.released_flag
FROM Table_A a,
     Table_B b,
     Table_C c
WHERE a.header_id = b.header_id
AND   c.line_id = b.line_id
AND   a.order_number = '123';

My desire output is as shown below:

   order_number | header_id | line_id | quantity | hold_price_id | released_flag
            123 |     80001 |   10001 | 1        | 2001          | Y
            123 |     80001 |   10002 | 3        | 2002          | Y
            123 |     80001 |   10003 | 5        | 2003          | N

However the query show me the below result:

order_number | header_id | line_id | quantity      | hold_price_id | released_flag
         123 |     80001 |   10001 | 1             | 2001          | Y
         123 |     80001 |   10001 | 3             | 2002          | Y
         123 |     80001 |   10001 | 5             | 2003          | N
         123 |     80001 |   10002 | 1             | 2001          | Y
         123 |     80001 |   10002 | 3             | 2002          | Y
         123 |     80001 |   10002 | 5             | 2003          | N
         123 |     80001 |   10003 | 1             | 2001          | Y
         123 |     80001 |   10003 | 3             | 2002          | Y
         123 |     80001 |   10003 | 5             | 2003          | N

Is it something wrong on my query? Please advice.

Thank you!

like image 312
Law Avatar asked Mar 30 '15 01:03

Law


2 Answers

You need to learn to use proper explicit join syntax. A simple rule: never use commas in the from clause. Always use explicit joins:

SELECT A.order_number, A.header_id, B.line_id, B.quantity,
       C.hold_price_id, C.released_flag
FROM Table_A a JOIN
     Table_B b
     ON a.header_id = b.header_id JOIN
     Table_C c
     ON c.header_id = b.header_id AND c.line_id = b.line_id
WHERE a.order_number = '123';
like image 176
Gordon Linoff Avatar answered Nov 15 '22 05:11

Gordon Linoff


You haven't joined all of the common keys, so you are getting Cartesian results. You needs to join a to c with header id, like so

SELECT A.order_number, A.header_id, B.line_id, B.quantity, C.hold_price_id, C.released_flag
FROM Table_A a,
     Table_B b,
     Table_C c
WHERE a.header_id = b.header_id
AND   c.line_id = b.line_id
AND   a.header_id = c.header_id
AND   a.order_number = '123';
like image 23
nomistic Avatar answered Nov 15 '22 05:11

nomistic