如果不匹配,请加入较少的字段

时间:2018-03-07 04:53:36

标签: sql sql-server-2016

假设我有以下问题:

select p.PetID, o.*
from Pet p
left join Owner o
on p.OwnerName = o.OwnerName
and p.Country = o.Country
and p.Address = o.Address
and p.Ref = o.Ref

如果Pet没有匹配,我想简化加入:

select p.PetID, o.*
from Pet p
left join Owner o
on p.OwnerName = o.OwnerName
and p.Country = o.Country
and p.Address = o.Address

如果仍然是0匹配我需要再次简化:

select p.PetID, o.*
    from Pet p
    left join Owner o
    on p.OwnerName = o.OwnerName
    and p.Country = o.Country

最后:

   select p.PetID, o.*
   from Pet p
   left join Owner o
   on p.OwnerName = o.OwnerName

我目前的解决方案:

插入临时表,然后从临时表中选择,其中ownerId为null并具有4个单独的查询。但我的数据集非常大,而且效率不高。

宠物桌 - 25列,1.5mil记录
所有者表 - 10列,3mil记录

1 个答案:

答案 0 :(得分:1)

您可以执行多个left join s:

select p.PetID, . . .
from Pet p left join
     Owner o1
     on p.OwnerName = o1.OwnerName and
        p.Country = o1.Country and
        p.Address = o1.Address and
        p.Ref = o1.Ref left join
     Owner o2
     on p.OwnerName = o2.OwnerName and
        p.Country = o2.Country and
        p.Address = o2.Address and
        o1.Ref is null left join
     Owner o3
     on p.OwnerName = o3.OwnerName and
        p.Country = o3.Country and
        o2.Ref is null left join
     Owner o4
     on p.OwnerName = o4.OwnerName and
        o3.Ref is null ;

您需要填写. . .以获取每个表格中的列。

相关问题