20.000行的层次结构父级子级

时间:2020-07-22 13:10:23

标签: sql

我有一个这样的表:enter image description here

我能够使用下面的代码创建indent(level),因此它为我提供了特定parentCode所需的功能,但是表中有20.000行。

;WITH items AS (
SELECT distinct a.Code,ParentCode,0 AS Indent       
FROM tblReport a
WHERE 
ParentCode = '71' 
UNION ALL
SELECT  i.Code,i.ParentCode, Indent + 1
FROM tblReport i
INNER JOIN items itms ON itms.Code = i.ParentCode
)
SELECT distinct Code, ParentCode,Indent FROM items 

enter image description here

如果我将parentCode设置为NULL,则查询将花费很长时间。它运行了几个小时,仍然没有返回数据。还有其他方法可以实现这一目标吗?我可以在服务器端或客户端执行此操作,因此,无论您使用javascript还是c#或SQL中的解决方案都没关系。

1 个答案:

答案 0 :(得分:0)

您的查询看起来不错。以下索引应提高查询的性能:

create index ix1 on tblReport (parentCode, Code);