如何获得一个在 WHERE 子句中使用 OR 的查询,在编译期间将其自身拆分为两个带有 UNION 的查询?如果我手动重写它,使用 UNION 的查询比单个查询快 100 倍,因为它可以在联合的每个查询中有效地使用不同的索引。有什么方法可以让优化器使用这种方法吗?
我有一个如下所示的查询:
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
where conditions1
and ((@param1 is null and cond3a) or (cond3b))
其中columnlist、joincond2、joincond3 和condition1 都是较长的表达式。关键在于 OR 中只有一个条件为真。
我一开始以为我可以重写它来进行联合,但后来我重复了columnlist、joincond2、joincond3和conditions1,这是大约20行SQL,将来可能需要大量维护。是否有我可以提供的提示或一些更好的方法来编写 WHERE 子句?提前致谢。
最佳答案
你可以分组
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
进入 View ,然后使用 union。
但是如果你可以迁移到sql2005/8, 您可以使用公共(public)表表达式。
with cte ( columnlist )
as (
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3 )
select columnlist from cte where ...
union
select columnlist from cte where ...
关于sql - 在 SQL Server 2000 中强制对 OR 使用 UNION 进行优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/372246/