2010-07-14 146 views
0

我有3個表。我正在使用Oracle 10g。帶外連接的SQL查詢幫助

我想從表A記錄,其中行不表C 存在,如果在表C相應行,那麼它應該滿足的條件,其中C_PRIAMRY = 1

Table_A 

A_ID, A_NAME, A_STATUS_CD, A_STATUS_DTE 
---------------------------------------- 
1  test1  NM   
2  test2  BB 
3  test3  CC 

Table_B 

B_ID  B_START_DATETIME  B_END_DATETIME 
-------------------------------------------- 
10   07-10-2010   08-10-2010 
20   07-10-2010   08-10-2010 


Table_C 

C_ID A_ID B_ID  C_PRIMARY 
------------------------------------- 
1  1  10   1 
2  1  10   0 
3  1  10   0 



select A.A_ID, A.A_NAME, A.A_STATUS_CD, A.A_STATUS_DTE, B.B_ID, B.B_START_DATETIME, C.C_PRIMARY 
    FROM TableA A, TableB B, TABLEC C 
WHERE A.A_ID = C.A_ID (+) AND C.B_ID = B.B_ID(+) AND C.PRIMARY(+) = 1   

我寫了這個查詢它不起作用。請提出任何想法。

謝謝

+0

讓人驚訝請問LEFT JOIN語法不在Oracle中工作? – Jeremy 2010-07-14 18:09:10

回答

3

考慮從(+)改寫:

select * from A, B where A.ID = B.A_ID(+) 

等效,更具可讀性left join

select * from A left join B on A.ID = B.A_ID 

將此應用於您的查詢,我得到:

select * 
from TableA A 
left join 
     TableC C 
on  c.a_id = a.a_id 
     and C.PRIMARY = 1 
left join 
     TableB B 
on  b.b_id = c.b_id 

這應該從中檢索所有的行,由C與行相匹配,其中primary = 1,從B.

與行相匹配的結果中不包括行的時候沒有找到匹配,使用inner join。例如,爲了找到所述的行,對此在C對應的行與primary = 1存在,但沒有相應的行中B:

select * 
from TableA A 
inner join 
     TableC C 
on  C.A_ID = A.A_ID 
     and C.C_PRIMARY = 1 
where not exists 
     (
     select * 
     from TableB B 
     where C.B_ID = B.B_ID 
     ) 
+0

Andomar, 如果表B中沒有行,則表C中也不會有任何行。 – nav100 2010-07-14 19:37:08

3

嘗試這種情況:

SELECT A.A_ID, A.A_NAME, a.A_STATUS_CD, A.A_STATUS_DTE, 
    B.B_ID, B.B_START_DATETIME, C.C_PRIMARY 
FROM TableA A LEFT JOIN TableC C ON A.A_ID = C.A_ID 
    LEFT JOIN TAbleB B ON B.B_ID = C.B_ID 
WHERE C.A_ID IS NULL OR C.PRIMARY = 1 
+0

+1與我的回答相同。 – 2010-07-14 18:17:31

+0

+1我認爲你比我更瞭解OP了:) – Andomar 2010-07-14 18:19:39