【问题标题】:Should I JOIN or should I UNION我应该加入还是应该联合
【发布时间】:2016-08-03 13:28:24
【问题描述】:

我尝试查询四个不同的表,第一个表是我将进行大部分查询的地方,但如果汽车中没有匹配项,我将查看其他表中的其他字段以查看如果 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

【问题讨论】:

  • 样本数据和预期结果会有所帮助
  • 通常JOIN 用于具有已定义关系的数据。例如:课程和学生。缺少可能的 Cars Towing Boats 没有参照关系,因此 JOIN 不适用于此处。
  • 拜托拜托,请停止使用那个过时的join syntax.
  • Simlpy写两个查询,Q1从cars中选择,如果没有返回行Q2从boats中选择。

标签: sql sql-server join union


【解决方案1】:

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

【讨论】:

  • 假设BoatsCars 具有相同的列,但无论如何都是+1。
  • NULLs 添加到不匹配的列的效果如何?因为就像我说的那样,我将主要在Cars 上查询,而不是频繁地查询其他表。将NULLs 添加到 UNION 中的其他表会导致任何问题吗?
  • @programmer117 。 . .如果其他表中不存在列,则绝对使用NULL 作为占位符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 2011-06-21
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多