考虑以下简单的DAG:
1->2->3->4
Run Code Online (Sandbox Code Playgroud)
还有一个表#bar,描述了这个(我正在使用SQL Server 2005):
parent_id child_id
1 2
2 3
3 4
//... other edges, not connected to the subgraph above
Run Code Online (Sandbox Code Playgroud)
现在假设我有一些其他任意标准来选择第一个和最后一个边,即1-> 2和3-> 4.我想用这些来查找我的图表的其余部分.
我可以写一个递归CTE如下(我使用的是MSDN中的术语):
with foo(parent_id,child_id) as (
// anchor member that happens to select first and last edges:
select parent_id,child_id from #bar where parent_id in (1,3)
union all
// recursive member:
select #bar.* from #bar
join foo on #bar.parent_id = foo.child_id
)
select parent_id,child_id from foo
Run Code Online (Sandbox Code Playgroud)
但是,这会导致边缘3-> 4被选中两次:
parent_id child_id
1 2
3 4
2 …Run Code Online (Sandbox Code Playgroud)