首页 > 解决方案 > SQL Server 将 Self-Join 更改为具有范围的 CTE

问题描述

我有一个很好的基于范围左连接的自连接查询。在上一个时期,查询的性能开始下降,我正在尝试通过将其迁移到 CTE 或任何其他解决方案来优化此查询。

select distinct Main.Id, Main.Name, Main.PolicyRef, Main.ExtCategoryId, Main.NodeLevel, Main.Description
from tbl1 as Main left join
     tbl1 as Cat
     on (Cat.LeftN between Main.LeftN and Main.RightN and Cat.RightN between Main.LeftN and Main.RightN
       OR
        Cat.LeftN between Main.RightN and Main.LeftN and Cat.RightN between Main.RightN and Main.LeftN
      ) and cat.Id=main.Id
where Cat.Id in (select CategoryRef from tbl2 where AccountRef=@AccountRef and ItemRef=@MId)


 set statistics io on

表“工作台”。扫描计数 0,逻辑读取 0,物理读取 0,预读读取 0,lob 逻辑读取 0,lob 物理读取 0,lob 预读读取 0。

表'tbl1'。扫描计数 1,逻辑读取 19903,物理读取 0,预读读取 0,lob 逻辑读取 0,lob 物理读取 0,lob 预读读取 0。

表'tbl2'。扫描计数 1,逻辑读取 123,物理读取 0,预读读取 0,lob 逻辑读取 0,lob 物理读取 0,lob 预读读取 0。

标签: sqlsql-server

解决方案


推荐阅读