Answers:
尝试:
where exists (select * ....
where Customers.orderId = ...
or Customers.secondaryId = ...
)
例如,如果您计划:
where orderId in (select value from ...)
or secondaryorderid in (select value from ...)
然后进行创建,以便仅调用一次子查询,并在其中构建OR子句。
where exists (select * from ...
where Customers.orderId = value
or Customers.secondaryOrderId = value
)
这样做的全部目的是确保复杂的子查询仅执行一次。对于CTE或用两个EXISTS替换两个IN都不会发生这种情况。
您的查询可能应该改写为exists
而不是in
有关更多示例,请参见此链接。
然后,您的查询看起来与
select *
from Customers C
where exists (select 'x' from ordertable o where c.orderid = o.orderid)
or exists (select 'x' from ordertable o where c.secondaryOrderId = o.orderid)
如果两个子查询相同,则可以删除其中的一个并合并它们
select *
from Customers C
where exists (select 'x' from ordertable o where c.orderid = o.orderid or c.secondaryOrderId = o.orderid)
为什么不使用Common Table Expression aka with
子句?它正是为此目的(以及其他目的)而设计的。
with orderIds as (
select orderId
from ...
)
select *
from Customers
where orderId in (select orderId from orderIds)
or secondaryOrderId in (select orderId from orderIds);
请参阅https://msdn.microsoft.com/zh-cn/library/ms175972%28v=sql.105%29.aspx以获取Microsoft的文档。