sql - 我应该加入还是应该联合

标签 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中有匹配项,我如何才能提取匹配的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

最佳答案

某种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);

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

随着您添加更多实体类型,不存在 链可能会变得更长。一种简单的解决方法是进行排序 - 假设您只想要一行:

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 行是微不足道的。

关于sql - 我应该加入还是应该联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36581666/

相关文章:

sql - 防止 Oracle 减去语句删除重复项

具有多个属性的 SQL 排序(按一致性排序)

sql - 如何在连接的聚合查询中聚合字段中的多行

SQL 查询 row_number() over partition by query result 在某些情况下返回错误

PHP/MYSQL Echo 使用join命令

SQL如何将一列拆分为多个变量列

sql-server - PK 和 FK 查找算法

sql-server - freetds 和 pyodbc 无法连接

MySQL:当连接表有多个结果时,为什么此选择查询找不到行?

MySQL错误没有意义?