我应该加入还是我应该加入联盟

时间:2016-04-12 18:51:28

标签: sql sql-server join union

我正在尝试查询四个不同的表,第一个表是我将进行大部分查询的地方,但如果在汽车中没有匹配,我会查看其他表中的其他字段以查看如果VIN参数匹配。

示例:

Select 
    c.id,
    c.VIN,
    c.uniqueNumber,
    c.anotheruniqueNumber
FROM Cars c, Boat b
WHERE
    c.VIN = @VIN(parameter),
    b.SerialNumber = @VIN

现在说Cars中没有匹配,但Boat中有匹配,我怎样才能将匹配的船记录与汽车记录相匹配?我试图加入表,但表没有唯一标识符来引用另一个表。

我试图弄清楚从参数中搜索所有表格的最佳方法是什么,但代码量最少。我考虑过做UNION ALL,但不确定我是否真的想要这种情况,因为记录的数量会变得非常大。

我目前正在使用SQL Server 2012。提前谢谢!

更新:

CAR table
ID  VIN               UniqueIdentifier      AnotherUniqueIdentifier
1   2002034434        HH54545445            2016-A23
2   2002035555        TT4242424242          2016-A24
3   1999034534        AGH0000034            2016-A25


BOAT table
ID  SerialNumber    Miscellaneous
1   32424234243     545454545445
2   65656565656     FF24242424242
3   20023232323     AGH333333333

如果@VIN参数与船标识符匹配,则为预期结果:

BOAT
ID  SerialNumber    Miscellaneous
2   65656565656     FF24242424242

1 个答案:

答案 0 :(得分:3)

某种union all可能是最好的方法 - 至少是使用正确索引的最快方法:

Select c.id, c.VIN, c.uniqueNumber, c.anotheruniqueNumber
from Cars c
where c.VIN = @VIN
union all
select b.id, b.VIN, b.uniqueNumber, b.anotheruniqueNumber
from Boats b
where b.VIN = @VIN and
      not exists (select 1 from Cars C where c.VIN = @VIN);

这假设您在每个表中都有相应的列(您的问题暗示为真)。

添加更多实体类型时,not exists链可能会变长。一个简单的方法是进行排序 - 假设您只需要一行:

select top 1 x.*
from (Select c.id, c.VIN, c.uniqueNumber, c.anotheruniqueNumber, 1 as priority
      from Cars c
      where c.VIN = @VIN
      union all
      select b.id, b.VIN, b.uniqueNumber, b.anotheruniqueNumber, 2 as priority
      from Boats b
      where b.VIN = @VIN 
     ) x
order by priority;

order by有轻微的开销。但坦率地说,从性能角度来看,排序1-4行是微不足道的。