单一选择的多个加入

时间:2018-06-13 09:47:25

标签: sql sql-server join select

我有以下查询:

select [signaleringid], label,  proces,  product from Signalering sig
JOIN ScreeningLabelAuthorizationLock p
ON sig.label = p.Value
union
select [signaleringid], label,  proces,  product from Signalering sig
JOIN ScreeningProcessAuthorizationLock q
ON sig.proces = q.Value
union
select [signaleringid], label,  proces,  product from Signalering sig
JOIN ScreeningProductAuthorizationLock r
ON sig.product = r.Value

如何在不重复3次相同Select查询的情况下实现相同的结果?我想要的只是1个选择查询,我从中单独加入3个不同的表,但最后结果都在一起。

编辑:

Signalering table: [label][proces][product]
ScreeningLabelAuthorizationLock table: [Value][Lock]
ScreeningProcessAuthorizationLock: [Value][Lock]
ScreeningProductAuthorizationLock: [Value][Lock]

1 个答案:

答案 0 :(得分:0)

由于您只使用表格Signalering中的列,因此您无需使用联接来获得此结果。一种解决方案是检查相应表中是否存在给定值。然后将exists表达式与where子句中的or语句组合在一起。通过这种方式,您将只获得符合一个或多个存在表达式的Signalering行。

select sig.[signaleringid], sig.label,  sig.proces,  sig.product 
from Signalering sig
where sig.label exists (select Value from ScreeningLabelAuthorizationLock)
or sig.proces exists (select Value from ScreeningProcessAuthorizationLock)
or sig.product exists (select Value from ScreeningProductAuthorizationLock)
group by sig.[signaleringid], sig.label,  sig.proces,  sig.product

另一个选择可能是使用左外连接

select sig.[signaleringid], sig.label,  sig.proces,  sig.product 
from Signalering sig
left outer join ScreeningLabelAuthorizationLock la on sig.label = la.Value
left outer join ScreeningProcessAuthorizationLock lp on sig.proces = lp.Value
left outer join ScreeningProductAuthorizationLock lpa on sig.product = lpa.Value
group by sig.[signaleringid], sig.label,  sig.proces,  sig.product