gpt4 book ai didi

.net - 检索所有子项及其子项,递归 SQL

转载 作者:行者123 更新时间:2023-12-04 17:28:18 24 4
gpt4 key购买 nike

考虑数据库中的以下行:

Id      |   Parent
__________________
1 null
2 1
3 2
4 3
5 null
6 5

每个 Id有一个 null Parent是“所有者”/“ super parent ”。

什么是最好的方法,表现明智,收集 parent 和他们的 child ?我应该使用 LINQ 存储过程 ?

我希望最终结果是 IEnumerable<IEnumerable<int>> .

最佳答案

在 SQL 中,您可以使用 CTE 进行查询。例如,要检索包含其父节点和树中最高父节点的节点列表:

declare @t table (id int, parent int)
insert @t (id, parent) values (1, null), (2,1), (3,2), (4,3), (5,null), (6,5)

; with cte as (
select id, parent, id as head
from @t
where parent is null
union all
select child.id, child.parent, parent.head
from @t child
join cte parent
on parent.id = child.parent
)
select *
from cte

这给出:
id  parent  head
1 NULL 1
2 1 1
3 2 1
4 3 1
5 NULL 5
6 5 5

请注意,我更改了您的示例数据,因此第 2 行不再是其自身的子项,而是第 1 行的子项。

关于.net - 检索所有子项及其子项,递归 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3299496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com