左外连接表中的空值

时间:2018-04-06 10:39:04

标签: oracle outer-join

我在Oracle尝试从2个表中进行选择时遇到这种情况:

表1

-------------
Col1   Col2
-------------
1      abc
2      aa
3      lab
4      mm
5      nn 
6      kk 
7      pp

表2

-----------
Col1   Col2
----------
  4    xxx

  7    yyy

(null) zzz

我想在我的select中包含Table2的所有行,包括(null)zzz。 我在做的是 -

SELECT column1, column2,….FROM Table1, Table2 Where table1.col1 = Table2.col1(+)

但它没有给我表2中的NULL值行。

我尝试在col1上使用左外连接的OR条件,但它不起作用。

SELECT column1, column2,…. FROM Table1, Table2 Where table1.col1 = Table2.col1(+) OR Table2.Col1 IS NULL

这是预期的输出:

    Col1 Table1.Col2 Table2.Col2
--------------------------------    
      1      abc     (null)

      2      aa      (null)

      3      lab     (null)

      4      mm       xxx

      5      nn      (null)

      6      kk      (null)

      7      pp       yyy

(null)      (null)    zzz

1 个答案:

答案 0 :(得分:2)

你想要的似乎是FULL OUTER JOIN

SQL Fiddle

查询1

SELECT 
    t1.COl1
    ,t1.col2
    ,t2.col2
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON
         ( t1.col1 = t2.col1 ) 
     ORDER BY Col1 

<强> Results

|   COL1 |   COL2 |   COL2 |
|--------|--------|--------|
|      1 |    abc | (null) |
|      2 |     aa | (null) |
|      3 |    lab | (null) |
|      4 |     mm |    xxx |
|      5 |     nn | (null) |
|      6 |     kk | (null) |
|      7 |     pp |    yyy |
| (null) | (null) |    zzz |

重要的建议是删除(+)外连接表示法并使用ANSI .. JOIN ON语法。