SQL:空列上的FULL OUTER JOIN

时间:2015-09-15 13:14:08

标签: sql oracle join outer-join

我想在几个列的两个表之间使用FULL OUTER JOIN,但是当两个列都为null时,在连接期间它们不被视为相等,因此我获得了两个不同的行。如何编写连接,因此空列被视为相等?

我已经设置了一个简化的例子:

create table t1 (
 id number(10) NOT NULL,
 field1 varchar2(50),
 field2 varchar2(50),
 CONSTRAINT t1_pk PRIMARY KEY (id)
);

create table t2 (
  id number(10) NOT NULL,
  field1 varchar2(50),
  field2 varchar2(50),
  extra_field number(1),
  CONSTRAINT t2_pk PRIMARY KEY (id)
);

insert into t1 values(1, 'test', 'test2');
insert into t2 values(1, 'test', 'test2', null);

insert into t1 values(2, 'test1', 'test1');
insert into t2 values(2, 'test1', 'test1', null);

insert into t1 values(3, 'test0', null);
insert into t2 values(3, 'test0', null, 1);

insert into t2 values(4, 'test4', 'test0', 1);

select *
from t1
full outer join t2 using (id, field1, field2);

获得的结果:enter image description here

预期结果:enter image description here

SQLFiddle

6 个答案:

答案 0 :(得分:2)

使用NVL()和唯一字符串替换NULL:

select t1.id,t1.field1,t1.field2,t2.extra_field
from t1
full outer join t2 ON
t1.id=t2.id 
AND NVL(t1.field1,'UID_INSTEAD_OF_NULL')=NVL(t2.field1,'UID_INSTEAD_OF_NULL')
AND NVL(t1.field2,'UID_INSTEAD_OF_NULL')=NVL(t2.field2,'UID_INSTEAD_OF_NULL')

SQLFiddle demo

答案 1 :(得分:2)

NVL可以应用于结果,因此在连接条件

中不需要任何功能
select
    nvl(t1.id, t2.id) id,
    nvl(t1.field1, t2.field1) field1,
    nvl(t1.field2, t2.field2) field2,
    extra_field
from t1
full outer join t2 on t1.id = t2.id AND t1.field1 = t2.field1 AND (t1.field2 = t2.field2 OR (t1.field2 IS NULL AND t2.field2 IS NULL));

答案 2 :(得分:0)

结果不容易区分数据中的NULL和表示连接失败的NULL。当要连接的数据中存在空值时,通常最好通过使用常规连接从结果中省略它们。 请看这个链接:https://technet.microsoft.com/en-us/library/ms190409(v=sql.105).aspx

select *
from t1, t2
where t1.id = t2.id and t1.field1 = t2.field1 and t1.field2 = t2.field2;

答案 3 :(得分:0)

一种解决方案是使用NVL并将NULL转换为标量值。

select *
from t1
full outer join t2 
  ON NVL(t1.id, 0) = NVL(t2.id, 0)
  AND NVL(t1.field1, 0) = NVL(t2.field1, 0)
  AND NVL(t1.field2, 0) = NVL(t2.field2, 0)
;

答案 4 :(得分:0)

内部Oracle自己的代码(例如,用于刷新实体化视图)使用Sys_Op_Map_NonNull()函数,这将使您的连接:

select *
from t1
full outer join t2 on (t1.id                         = t2.id and
                       t1.field1                     = t2.field2 and
                       Sys_Op_Map_NonNull(t1.field2) = Sys_Op_Map_NonNull(t2.field2));

我不确定它的使用是否得到官方支持,或者是否已经开始公开记录它。

答案 5 :(得分:0)

此解决方案维护using子句的使用,但删除了包含null的using子句中的一列(field2)。而是在选择列表中合并field2。

select id
     , field1
     , coalesce(t1.field2,t2.field2) field2
     , extra_field
from t1
full outer join t2 using (id, field1); --field2 removed from using clause.