gpt4 book ai didi

sql - 为什么 CTE(递归)没有并行化(MAXDOP=8)?

转载 作者:行者123 更新时间:2023-12-01 04:09:58 25 4
gpt4 key购买 nike

我们有相当大的机器 100GB+ 内存和 8+ 个内核。服务器范围 MAXDOP=8。

T_SEQ_FF rowcount = 61692209, size = 2991152 KB  

UPD 1:
T_SEQ_FF有两个索引:
1) create index idx_1 on T_SEQ_FF (first_num)
2) create index idx_2 on T_SEQ_FF (second_num)

T_SEQ_FFfirst_num , second_num pairs应该在 cte 之后提供序列的 nums:
;with first_entity as ( 
select first_num from T_SEQ_FF a where not exists (select 1 from T_SEQ_FF b where a.first_num = b.second_num)
) ,
cte as (
select a.first_num, a.second_num, a.first_num as first_key, 1 as sequence_count
from T_SEQ_FF a inner join first_entity b on a.first_num = b.first_num
union all
select a.first_num, a.second_num, cte.first_key, cte.sequence_count + 1
from T_SEQ_FF a
inner join cte on a.first_num = cte.second_num
)
select *
from cte
option (maxrecursion 0);

但是当我运行这个查询时 - 我只看到没有并行的串行查询计划。
如果我 删除 来自上述查询的 CTE 的第二部分:
union all 
select a.first_num, a.second_num, cte.first_key, cte.sequence_count + 1
from T_SEQ_FF a
inner join cte on a.first_num = cte.second_num

然后我可以看到查询计划变成 并行化 使用重新分区和收集流。

所以我可以总结一下,这是因为 递归 CTE SQL Server 在处理此查询时未使用并行性。

我相信在拥有大量免费资源的大型机器上,并行应该有助于更快地完成查询。

现在它运行约 40-50 分钟。

您能否建议我们如何使用尽可能多的资源来更快地完成查询?

CTE 是唯一的选择,因为我们需要填充来自 first_num - second_num 的序列。对,这些序列可以是任何长度。

最佳答案

我会尝试重写 CTE 以删除其中一个步骤,即

;cte as ( 
select a.first_num, a.second_num, a.first_num as first_key, 1 as sequence_count
from T_SEQ_FF a where not exists (select 1 from T_SEQ_FF b where a.first_num = b.second_num)
union all
select a.first_num, a.second_num, cte.first_key, cte.sequence_count + 1
from T_SEQ_FF a
inner join cte on a.first_num = cte.second_num
)
select *
from cte
option (maxrecursion 0);

如果只有一个根元素,最好将其作为变量传递到查询中,以便查询优化器可以使用该值。

要尝试的另一件事是更改查询以获取没有子查询的根元素,即 second_num 为 null 或 first_num = second_num。

关于sql - 为什么 CTE(递归)没有并行化(MAXDOP=8)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com