我的sql表有两列Parent,Child没有主键。数据巨大。 现在,我需要开发一个Parent-> Child-> child of children的层次结构。
例如:表格中的数据如下所示:
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->所有孩子的所有孩子,依此类推:Group1 - 1,2,3,10,11,5,7,13; Group2-4,15; Group3 - 7,17; Group4 - 8,20。有人可以使用sql或c#来指导我实现这一目标的最佳/最有效方法吗?
谢谢!
答案 0 :(得分:2)
你可以在SQL中做到这一点。语法有点依赖于RDBMS,但通常情况下(你最好在你的子列和父列上创建一些索引,或者将它复制到临时表然后创建索引,否则它可能是slooow)
;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)