【问题标题】:CTE query plan for complex query - triple run of the same init query - why?复杂查询的 CTE 查询计划 - 相同初始化查询的三次运行 - 为什么?
【发布时间】:2010-10-01 21:50:55
【问题描述】:

这很难解释,但我会尝试。

正如您在所附的 query_plan 图片上看到的(这是 “All in one place” 查询的查询计划,如下所述),有 3 个几乎相同的“块” - 我的问题是为什么?在我看来,当我有“all in one”(见下文)查询时,“Init”块(相当重)会使用不同的过滤器运行 3 次,而不是 SPOOLED 并在以后重复使用。

此查询执行时间约为 45 秒。 它的查询可以用以下形式呈现:

-- Complex "All in One place" Query
WITH init as (
  Init1 complex query here  -- (10 sec to run) if executed alone
)
, step1 as ( select * from init .. joins... where ... etc ), 
step2 as ( select *, row_number() over(__condition__) as rn from step1 where _filter1_)
, step3 as ( select * from step2 where __filter2_), 
.... some more steps could be here ....
select * 
into target_table
from step_N;
-- 45sec CPU time 

这里重要的是我在“WITH”子句中顺序使用那些 Step1、Step2、...、StepN 表 - 步骤 1 使用 INIT 表,所以 Step2 使用 Step1 表,Step3 使用 Step2 表等。我需要这个由于排名不同,我会在稍后用于过滤的每个步骤之后进行处理。

如果把这个复杂的 CTE 查询改成(我把 Init 查询的结果放到表中,然后处理其他步骤不变):

-- Complex query separated from the rest of the query
 with Init as ( 
   The same Init1 complex query here
) 
select * 
into test_init 
from init;
-- 10sec CPU time

with step1 as ( select * from test_init .. joins... where ... etc ), 
step2 as ( select *, row_number() over(__condition__) as rn from step1 where _filter1_)  , 
step3 as ( select * from step2 where __filter2_), 
.... some more steps could be here ....
select * 
into target_table
from step_N; 
-- 5sec CPU time

我有大约 15 秒的执行时间,这对我来说似乎没问题。因为 10 秒是第一个难以改进的复杂查询。

所以我不能得到这个 MS Sql server 2005 的行为?有人可以向我解释一下吗?我想这很有趣!

【问题讨论】:

    标签: sql-server-2005 tsql sql-execution-plan


    【解决方案1】:

    看起来优化器认为在不同条件下运行三次查询会更快。优化器并不总是正确的。

    使用临时表来强制 SQL Server 首先执行整个复杂查询实际上很常见。通常,您会使用临时表而不是 test_init

    insert into #temptbl select * from Init
    

    SQL Server 还使用临时表来存储连接和子查询的结果。使用临时表不会对性能产生负面影响。

    【讨论】:

    • 我们稍后有时会使用表格进行质量检查。在适当的地方使用临时表。嗯......有没有办法“告诉”MS SQL最好将结果放入假脱机并重用?写一个计划,提示,什么?
    • @zmische - 计划提示很可能,但请记住,假脱机将只是 tempdb 中的工作表。
    • 是的,你是对的。但我打算在一个查询中完成这项工作,而不需要额外的 select .. into from。如果从 MS SQL 服务器的角度来看,它甚至更多。 %) 无论如何谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多