WHERE 子句中的优化似乎不适用于 UNION

Optimization in WHERE clause seems to be not working with UNION

我尝试了以下格式的 SQL 脚本。 (有多个联接生成 set1、set2 和 set3,但为简单起见将其删除)。

SELECT * FROM (
    SELECT * FROM Set1
    WHERE someConditions
    UNION
    SELECT * FROM Set2
    WHERE someConditions
    UNION 
    SELECT * FROM Set3
    WHERE @include = 1 AND otherConditions..
) as t
ORDER BY ...

人们会期望当 @include = 0 时,最后一个 UNION 的全部将被忽略。这也是我在查找有条件地做 UNION.

时所看到的

但我不是这样;即使在 @include = 0 时,查询也需要很长时间才能执行。如果我注释掉最后一部分,查询将执行得更快。

SELECT * FROM (
    SELECT * FROM Set1
    WHERE someConditions
    UNION
    SELECT * FROM Set2
    WHERE someConditions
    --UNION 
    --SELECT * FROM Set3
    --WHERE @include = 1 AND otherConditions..
) as t
ORDER BY ...

为什么编译器无法识别它?在这种情况下有什么方法可以优化查询吗?

对我来说,OPTION(RECOMPILE) 在类似的测试中运行良好 set-up - 在没有提示的情况下重用糟糕的计划(假设之前 运行 和 @include = 1)但是创建了一个新的,使用 RECOMPILE 时更好的计划。

如果这对您不起作用,您可以尝试使用 IF 分成两个不同的语句,例如:

BEGIN
IF @include = 1 
BEGIN

    SELECT * FROM Set1
    WHERE someConditions
    UNION
    SELECT * FROM Set2
    WHERE someConditions
    UNION 
    SELECT * FROM Set3
    WHERE otherConditions..

END

ELSE 
BEGIN
    SELECT * FROM Set1
    WHERE someConditions
    UNION
    SELECT * FROM Set2
    WHERE someConditions
END
END