左外连接和联盟

时间:2014-01-17 04:39:10

标签: sql oracle join union

我有两个表有一个父表,并通过其父表通过外键关联,即

TableP
 -----------------
| C1  | P2  | P3  |
 -----------------
   0    P2    P3

TableA
 -----------------
| C1  | A2  | A3  |
 -----------------
   0    A21   A31
   0    A22   A32

TableB
 -----------------
| C1  | B2  | B3  |
 -----------------
   0    B21   B31
   0    B22   B32

我需要的是在以下结果集中提取数据:

 ---------------------------------
| C1  |  A2  |  A3  |  B2  |  B3  |
 ---------------------------------
   0     A21   A31    NULL   NULL
   0     A22   A32    NULL   NULL
   0    NULL   NULL    B21    B31
   0    NULL   NULL    B22    B32

这可以通过LEFT OUTER JOINUNION的组合来实现吗?

更新

由于其中一位评论者回答了问题,但没有以答案的形式回答,这里的解决方案对我有用:

SELECT p.c1, a.a2 a2, a.a3 a3, NULL b2, NULL b3 
FROM tablep p LEFT OUTER JOIN tablea a on a.c1 = p.c1 
UNION 
SELECT p.c1, NULL a2, NULL a3, b.b2 b2, b.b3 b3 
FROM tablep p LEFT OUTER JOIN tableb b on b.c1 = p.c1;

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT P.C1,A.A2,A.A3,B.B2,B.B3 FROM TableP P 
LEFT OUTER JOIN TableA A ON P.C1 = A.C1
LEFT OUTER JOIN TableB B ON P.C1 = B.C1

根据您的要求使用了Left Outer Join,不需要Union

答案 1 :(得分:0)

尝试此操作(未经测试),如果存在语法错误,请进行更改。

select coalesce(taba.p1,tabb.p1), taba.a2, taba.a3, tabB.b2, tabB.b3
  from (select 'A'||to_char(rownum) RR, a2, a3, tablep.p1 p1
          from tablea JOIN TABLEP ON (tablea.p1 = tablep.p1)) taba
     FULL OUTER JOIN  
       (select 'B'||to_char(rownum) RR, b2, b3, tablep.p1 p1
          from tableb JOIN TABLEP ON (tableb.p1 = tablep.p1)) tabB
    on (taba.rr = tabB.rr and tabB.p1 = tabA.p1);

答案 2 :(得分:0)

假设TableA.A2始终不等于TableB.B2

SELECT  tableP.C1,tableA.A2,tableA.A3,tableB.B2,tableB.B3
FROM tableA,tableB,tableP
WHERE tableP.C1 = tableA.C1
  AND tableP.C1 = tableB.C1
  And tableA.A2 = tableB.B2(+)
UNION ALL
SELECT  tableP.C1,tableA.A2,tableA.A3,tableB.B2,tableB.B3
FROM tableA,tableB,tableP
WHERE tableP.C1 = tableA.C1
  AND tableP.C1 = tableB.C1
  And tableB.B2 = tableA.A2(+)