-4

我有两列父、子没有主键的 sql 表。数据是巨大的。现在,我需要开发一个 Parent->Child->children of child 的层次结构。

例如:表中的数据如下所示:

Parent Child
  1      2
  1      3
  1      10
  1      11
  2      5
  2      10
  2      7
  3      1
  3      13
  4      15
  7      17
  8      20

现在,我需要 Parent->Children->All children of All children 等在一个组下:Group1 - 1,2,3,10,11,5,7,13; 2-4,15 组;第 3 组 - 7,17;第 4 组 - 8,20。有人可以指导我使用 sql 或 c# 实现这一目标的最佳/有效方法吗?

谢谢!

4

1 回答 1

2

那么你可以在SQL中做到这一点。语法有点取决于 RDBMS,但通常类似于(您最好在子列和父列上创建一些索引或将其复制到临时表然后创建索引,否则可能会很慢)

;with CTE as (
    select Parent as ID, Child as Child, 1 as num
    from temp
    where Parent not in (select Child from temp)

    union all

    select C.ID, p.Child as Child, num + 1 as num
    from temp as p
        inner join CTE as C on C.Child = p.Parent
)
select
    C.ID,
    stuff(
        (
            select ', ' + cast(t.Child as nvarchar(max))
            from CTE as t
            where t.ID = C.ID
            order by t.num, t.Child
            for xml path(''), type
        ).value('.', 'nvarchar(max)')
    , 1, 2, '')
from CTE as C
group by C.ID
option (maxrecursion 0)

SQL 提琴示例

于 2013-08-01T19:37:08.320 回答