1

我想知道是否可以优化此类查询。我已经大大简化了它,你看到了它的核心。

with Rec (Id,Name,ParentId)
as
(
    select Id,Name,ParentId from Departments where ParentId is null
    union all
    select d.Id, d.Name, d.ParentId from Departments d join Rec r on 
    (d.ParentId=r.Id)
)
select q.* from (
select ROW_NUMBER() OVER (ORDER BY r.Id DESC) AS [ROW_NUMBER], r.* from Rec r
) as q
where q.[ROW_NUMBER] between 100 and 200

它的作用是分层查询下属部门,然后对其进行测距。

我最终制定了一个庞大的执行计划,并想知道是否可以以不同的方式完成。

谢谢你。

4

1 回答 1

1

考虑到以下假设,我认为它可能会更好一些:

  1. 您有正确的 ParentId 索引
  2. 您从表中检索了大量数据(大部分列)

可以做什么:为了减少 io 子系统的负载,我们可以首先编写一个 Id 列表,对它们进行分页(即按 RowNumber 过滤),然后才包括所有其他列。这将有效地导致使用 ParentId 的索引,考虑到上述两个假设,这应该更快。

所以这是我“亲自”提出的建议:

with Rec (Id,ParentId)
as
(
    select Id,ParentId from Departments where ParentId is null
    union all
    select d.Id, d.ParentId from Departments d join Rec r on 
    (d.ParentId=r.Id)
),
Paged 
as
(
    select * from (
        select ROW_NUMBER() OVER (ORDER BY r.Id DESC) AS [ROW_NUMBER], r.* from Rec r
    ) as q
    where q.[ROW_NUMBER] between 100 and 200
)
select * 
from 
    Paged
    inner join Departments d on d.Id = Paged.Id
于 2009-08-06T14:21:57.657 回答