4

有没有办法在类似的表中递归读取记录并按深度级别排序?

#table:

id int    |   parent int    |   value string
--------------------------------------------
1             -1                some
2             1                 some2
3             2                 some3
4             2                 some4
5             3                 some5
6             4                 some6
7             3                 some5
8             3                 some5
9             8                 some5
10            8                 some5

那么有没有一种方法可以递归地选择结果表看起来像这样的位置。

select * from #table where id=3 

id int      | parent int      | value string   |  depth  
--------------------------------------------------------
3             2                 some3             0
5             3                 some5             1
7             3                 some5             1 
8             3                 some5             1
9             8                 some5             2
10            8                 some5             2

所以如果我选择 id=3 我会看到 id=3 和孩子的递归

谢谢

4

2 回答 2

8
;with C as
(
  select id,
         parent,
         value,
         0 as depth
  from YourTable
  where id = 3
  union all
  select T.id,
         T.parent,
         T.value,
         C.depth + 1
  from YourTable as T
    inner join C  
      on T.parent = C.id
)
select *
from C

SE-数据

于 2012-04-25T07:32:49.103 回答
4

您可以使用 CTE,特别是 rCTE 来完成。

请参阅,以及以获取更多信息。

要遵循的示例:

WITH sampleCTE (id, parent, value, depth)
    AS (
        -- Anchor definition
        SELECT id
            , parent
            , value
            , 0
        FROM #table
        WHERE id = @targetId
        -- Recursive definition
        UNION ALL
        SELECT child.id
            , child.parent
            , child.value
            , sampleCTE.depth + 1
        FROM #table child 
            INNER JOIN sampleCTE ON sampleCTE.id = child.parent
    )
于 2012-04-25T07:32:57.553 回答