在列上加入2个表,其中包含一些缺少的条目

时间:2017-01-04 23:28:56

标签: sql oracle

考虑这两个表:

CustAddress

Name             Address
----             -------
John             116 States Ave
Mike             404 16th Street

CustPhone

Name             Phone
----             -------
John             342-345-456
Smith             678-435-567

如何在Oracle中将这些结果组合成这样的结果:

地址和电话的客户信息:

Name             Phone               Address
----             -------             -------
John             342-345-456         116 States Ave
Smith            678-435-567
Mike                                 404 16th Street

Full Outer Join没有帮助,因为我最终丢失了一些数据。

这是一个可以玩的SQL小提琴: http://sqlfiddle.com/#!9/ebb9b/1

2 个答案:

答案 0 :(得分:4)

使用full join

select coalesce(ca.name,cp.name) as name, cp.phone, ca.address
from custaddress ca
full join custphone cp on ca.name=cp.name

或者使用union all假设每个表中每个名称最多只有一条记录。

select name,max(phone) as phone,max(address) as address
from (select name,phone,null as address from custphone
      union all
      select name,null,address from custaddress
     ) x
group by name

答案 1 :(得分:0)

有点难看,但

select Names.Name, CustAddress.Address, CustPhone.Phone from
(select Name from CustAddress union select Name from CustPhone) as Names
left join CustAddress on Names.Name = CustAddress.Name
left join CustPhone on Names.Name = CustPhone.Name;