需要消除连接和联合中的欺骗

时间:2015-12-23 05:42:54

标签: oracle union outer-join

任何人都可以帮助我吗

query::
select Ext_Acct,date_opened,last_date_flown,Sender from
table1 T1,table2 T2
where T1.Ext_acct(+)=T2.Ext_acct
union
select Ext_Acct,date_opened,last_date_flown,Sender from
table1 T1,table2 T3
where T1.Ext_acct(+)=T3.Ext_acct

数据我有::

表1

Ext_Acct    date opened last date flown
AAA dd/mm/yyyy  dd/mm/yyyy
BBB dd/mm/yyyy  dd/mm/yyyy
CCC dd/mm/yyyy  dd/mm/yyyy

表2

Ext_Acct    Sender  
AAA XXX 

表3

Ext_Acct    Sender  
BBB YYY 
CCC XXX

预期结果::

Ext Acct    date opened last date flown Sender
AAA dd/mm/yyyy  dd/mm/yyy   XXX
BBB dd/mm/yyyy  dd/mm/yyy   YYY
CCC dd/mm/yyyy  dd/mm/yyy   XXX

结果得到了::

Ext Acct    date opened last date flown Sender
AAA dd/mm/yyyy  dd/mm/yyy   XXX
AAA         
BBB dd/mm/yyyy  dd/mm/yyy   YYY
BBB         
CCC dd/mm/yyyy  dd/mm/yyy   XXX
CCC 

2 个答案:

答案 0 :(得分:1)

在T2和T3上尝试结合

select t1.Ext_Acct,
        t1.date_opened,
        t1.last_date_flown,
        t2.Sender 
from
      table1 T1,
       (select Ext_Acct, Sender from Table2 
        union 
        select Ext_Acct, Sender from Table3) T2
where T1.Ext_Acct=T2.Ext_Acct(+)

答案 1 :(得分:0)

您可以尝试DISTINCT

select DISTINCT T1.Ext_Acct,T1.date_opened,T1.last_date_flown,T2.Sender from
table1 T1,table2 T2
where T1.Ext_acct(+)=T2.Ext_acct
union
select T1.Ext_Acct,T1.date_opened,T1.last_date_flown,T3.Sender from
table1 T1,table2 T3
where T1.Ext_acct(+)=T3.Ext_acct

但我建议不要使用IMPLICIT JOINS并开始使用EXPLICIT JOINS,因为当有大量数据时它更准确。

SELECT DISTINCT T1.Ext_Acct,T1.date_opened,T1.last_date_flown,T2.Sender 
FROM TABLE1 T1 RIGHT JOIN TABLE2 T2
ON T1.Ext_acct = T2.Ext_acct
UNION
SELECT  T1.Ext_Acct,T1.date_opened,T1.last_date_flown,T3.Sender 
FROM TABLE1 T1 RIGHT JOIN TABLE3 T3
ON T1.Ext_acct = T3.Ext_acct