只有在一个表oracle中不为空时才连接两列

时间:2015-12-15 06:35:04

标签: oracle join null

我有一张桌子

ID | Name | City
1  |Jack  | Null
2  |Tom   | Null

表b

ID | Name | City
1  |Jack  | Dever
2  |Tom   | Dallas

如果在表a中它们不为null,我需要编写一个查询来按id,name和city连接这两个表。但是这三列中的任何一列对于每一行都可以为空。

我在下面写了一个,但数据增长时表现不好

Select * from a, b 
Where (a.id is not null and a.id=b.id or a.id is null) and
(a.name is not null and a.name=b.name or a.name is null) and
(a.city is not null and a.city=b.city or a.city is null)

基本上,当表a中的列不为空时,我需要加入列。 你能否对此有所了解? 非常感谢!

1 个答案:

答案 0 :(得分:0)

ATTEMPT I: 这会是你需要的吗?它似乎做了我可以从你的问题中读出的内容。

with a as (select 1 id, 'Jack' name, null    city from dual
            union all
            select 2 id, 'Tom'  name, null    city from dual
            union all
            select 3 id, 'Mike' name, 'Miami'   city from dual)
     ,b as (select 1 id, 'Jack' name, 'Dever'  city from dual
            union all
            select 2 id, 'Tom'  name, 'Dallas' city from dual
            union all
            select 3 id, 'Mike' name, 'Boise'   city from dual)
select b.* 
  from b
  left outer join a
    on a.id   = b.id
   and a.name = b.name
 where b.city  = nvl(a.city, b.city);

如果没有,请咨询结果或可能在indata中需要更改的内容。

更新I: 为了允许所有列都可以为null,这可能是一种方法。我已经为我认为你所描述的条件添加了testdata。它给出了我认为你正在寻找的结果。

with a as (select 1 id, 'Jack' name, null    city from dual
            union all
            select 2 id, 'Tom'  name, null    city from dual
            union all
            select 3 id, 'Mike' name, 'Miami'   city from dual
            union all
            select 4 id, 'Don' name, null   city from dual
            union all
            select 5 id, null name, 'London'   city from dual
            union all
            select null id, 'Erin' name, 'Berlin'   city from dual
           )
     ,b as (select 1 id, 'Jack' name, 'Dever'  city from dual
            union all
            select 2 id, 'Tom'  name, 'Dallas' city from dual
            union all
            select 3 id, 'Mike' name, 'Boise'   city from dual
            union all
            select 4 id, 'Don' name, 'Dover'   city from dual
            union all
            select 5 id, 'Lis' name, 'London'   city from dual
            union all
            select 6 id, 'Erin' name, 'Berlin'   city from dual
           )
select b.*, a.* 
  from b
  inner join a
    on b.id   = nvl(a.id,   b.id) 
   and b.name = nvl(a.name, b.name)
   and b.city = nvl(a.city, b.city)
order by 1;