如何使用旧式Oracle语法进行完全外部联接

时间:2013-03-27 11:12:25

标签: oracle join oracle8

对于每个表,我有两个具有相同列,Item Code和Qty的表:

TABLE A                    TABLE B
--------------             -------------
X    2                      X   1
Y    1                      S   2
Z    5                      Z   5

我的目标是得到这样的结果:

Table C
---------------
X  2  1
Y  1  0
S  0  2

我只需要两个表中qty不同的项目(包括应显示为零的空值。

注意:我使用的是Oracle8,因此无法使用ANSI FULL OUTER JOIN。

5 个答案:

答案 0 :(得分:12)

编辑,由于该问题特定于不使用ANSI语法的Oracle 8,因此以下内容应该有效:

select col1, 
  nvl(a_col2, 0) as a_col2, 
  nvl(b_col2, 0) as b_col2
from 
( 
  select a.col1, a.col2 as a_col2, b.col2 as b_col2 
  from TableA a, TableB b
  where a.col1 = b.col1(+)
  union
  select b.col1, a.col2 as a_col2, b.col2 as b_col2 
  from TableA a, TableB b
  where a.col1(+) = b.col1 
)      
where a_col2 <> b_col2
  or (a_col2 is null or b_col2 is null)

SQL Fiddle with Demo。这将返回:

| COL1 | A_COL2 | B_COL2 |
--------------------------
|    S |      0 |      2 |
|    X |      2 |      1 |
|    Y |      1 |      0 |

如果您使用的是支持ANSI语法的Oracle版本,则可以使用以下FULL OUTER JOIN

select 
  coalesce(a.col1, b.col1) col1, 
  coalesce(a.col2, 0) a_col2, 
  coalesce(b.col2, 0) b_col2
from tablea a
full outer join tableb b
  on a.col1 = b.col1
where a.col2 <> b.col2
  or (a.col2 is null or b.col2 is null);

请参阅SQL Fiddle with Demo

答案 1 :(得分:4)

该查询的另一篇文章应该适用于8和(可能是早期版本)。

它既不使用FULL JOIN也不使用可怕的(+)语法进行连接,所以即使升级过程也不应该使用它。

假设桌子上已经没有Null,您也不需要COALESCE()NVL()

SELECT  a.col1, 
        a.col2 AS a_col2, 
        b.col2 AS b_col2
FROM    TableA a, TableB b
WHERE   a.col1 = b.col1
  AND ( a.col2 <> b.col2
     OR a.col2 IS NULL
     OR b.col2 IS NULL
      )

UNION ALL

SELECT  col1, col2, 0
FROM    TableA a
WHERE   NOT EXISTS
        ( SELECT  *
          FROM    TableB b
          WHERE   a.col1 = b.col1
        )

UNION ALL

SELECT  col1, 0, col2
FROM    TableB b
WHERE   NOT EXISTS
        ( SELECT  *
          FROM    TableA a 
          WHERE   a.col1 = b.col1
        ) ; 

SQL-Fiddle

进行测试

答案 2 :(得分:2)

select code, nvl(a.qty,0) a, nvl(b.qty,0) b
from tableA a full join tableB b using(code)
where decode(a.qty, b.qty, 0) is null

fiddle

答案 3 :(得分:2)

另一种选择:

select
  full_list.item_code,
  nvl(table_a.qty,0) table_a_qty,
  nvl(table_b.qty,0) table_b_qty
from
  (select item_code from table_a
   union
   select item_code from table_b) full_list,
  table_a,
  table_b
where
  full_list.item_code = table_a.item_code(+) and
  full_list.item_code = table_b.item_code(+)

答案 4 :(得分:0)

以下查询应该正常工作:

SELECT * FROM (
  SELECT nvl(a.c1, b.c2), nvl(a.col1, 0) qty1, nvl(b.col2, 0) qty2 FROM a FULL OUTER JOIN b ON a.c1 = b.c2
) where qty1 != qty2;

http://sqlfiddle.com/#!4/d37ff/5/0

相关问题