Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 我应该加入还是加入工会_Sql_Sql Server_Join_Union - Fatal编程技术网

Sql 我应该加入还是加入工会

Sql 我应该加入还是加入工会,sql,sql-server,join,union,Sql,Sql Server,Join,Union,我尝试查询四个不同的表,第一个表是我将执行大部分查询的表,但是如果在car中没有匹配项,我将查看其他表中的其他字段,以查看VIN参数是否匹配 例如: Select c.id, c.VIN, c.uniqueNumber, c.anotheruniqueNumber FROM Cars c, Boat b WHERE c.VIN = @VIN(parameter), b.SerialNumber = @VIN 现在假设我在汽车中没有匹配项,但在船

我尝试查询四个不同的表,第一个表是我将执行大部分查询的表,但是如果在car中没有匹配项,我将查看其他表中的其他字段,以查看VIN参数是否匹配

例如:

Select 
    c.id,
    c.VIN,
    c.uniqueNumber,
    c.anotheruniqueNumber
FROM Cars c, Boat b
WHERE
    c.VIN = @VIN(parameter),
    b.SerialNumber = @VIN
现在假设我在
汽车
中没有匹配项,但在
中有匹配项,那么我如何才能提取匹配的船记录与汽车记录?我已尝试联接这些表,但这些表没有引用其他表的唯一标识符

我试图找出用最少的代码搜索所有参数表的最佳方法。我考虑过使用
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;

按订购的
有一点开销。但坦率地说,从性能的角度来看,排序1-4行是微不足道的。

示例数据和预期结果通常有助于
JOIN
用于具有定义关系的数据。课程和学生。除了可能的汽车和拖船之外,没有参考关系,因此这里不适用
JOIN
。请停止使用过时的Simlpy,写两个查询,Q1从
cars
中选择,如果它没有返回任何行,则Q2从
boats
中选择。这是假设
boats
cars
具有相同的列,但无论如何为+1。将
NULL
添加到不匹配的列中会有多大效果?因为就像我说的,我将主要查询
Cars
,而不是其他表。将
NULL
s添加到UNION中的其他表会导致任何问题吗?@programmer117。如果其他表中没有列,则一定要使用
NULL
作为占位符。