加入null

时间:2015-01-13 08:36:42

标签: sql oracle join oracle11g

我有两个表,我想在其中加入空值。

我的第一张桌子的样本数据(A_TEST):

+--+----+
|ID|NAME|
+--+----+
|  |a   |
|1 |b   |
|1 |c   |
+--+----+

我的第二张桌子的样本数据(B_TEST):

+--+----+
|ID|NAME|
+--+----+
|1 |d   |
|2 |e   |
|3 |f   |
+--+----+

我需要通过加入a_test.id = b_test.id来实现结果,如果其中有空值,我也需要获取它们。所以我尝试编写如下查询,

select a_test.id,a_test.name,b_test.id,b_test.name
from a_test,b_test
where (a_test.id = b_test.id
or a_test.id is null);

我输出如下,

+--+----+--+----+
|ID|NAME|ID|NAME|
+--+----+--+----+
|  |a   |1 |d   |
|  |a   |2 |e   |
|  |a   |3 |f   |
|1 |b   |1 |d   |
|1 |c   |1 |d   |
+--+----+--+----+

但是我的预期结果是,因为我的a_test中有id 1,我还需要来自b_test的相应行。参见下面的输出

+--+----+--+----+
|ID|NAME|ID|NAME|
+--+----+--+----+
|  |a   |1 |d   |
|1 |b   |1 |d   |
|1 |c   |1 |d   |
+--+----+--+----+

我尝试了外连接,但这也没有给我预期的输出。

4 个答案:

答案 0 :(得分:1)

您自己的查询几乎是正确的(尽管您不应该使用容易出错的逗号分隔连接,这些连接在二十年前已经过时了)。您只缺少在a_test.id为null时必须匹配的条件(即:b_test.id必须在表a_test中)。

select 
  a.id as a_id,
  a.name as a_name,
  b.id as b_id,
  b.name as b_name
from a_test a
join b_test b on 
  (a.id = b.id) 
 or
  (a.id is null and b.id in (select id from a_test));

SQL小提琴:http://www.sqlfiddle.com/#!4/fae22/2

答案 1 :(得分:0)

无论您的要求是多么奇怪和毫无意义,此查询都会为您提供预期结果:

select A.*, B.*
from a_test A
    join b_test B
        on A.id = B.id
union all
select A.*, B.*
from a_test A
    cross join b_test B
where A.id is null
    and exists (
        select 1
        from a_test Ax
        where Ax.id = B.id
    )
order by 2, 4
;

享受!

答案 2 :(得分:0)

如果a_test.id NULL在加入时应该被视为1,请使用COALESCE和子查询来查找替换值(由您自己计算,只需确保它不会返回多行):

select a_test.id,a_test.name,b_test.id,b_test.name
from a_test,b_test
where COALESCE(a_test.id,(select integervalue from sometable)) = b_test.id

答案 3 :(得分:0)

select a_test.id,a_test.name,b_test.id,b_test.name
from a_test,b_test
where a_test.id = b_test.id(+)

但是,当a_test.id为null或缺失时,您想看到什么?