0

我想找到DAG的拓扑排序。我们可以将一个递归查询的输出用于另一个递归查询吗?

create table topo(
v1 int, 
v2 int 
); 

Insert into topo values (1,3),(2,5),(3,4),(4,5),(4,6),(5,7),(6,5),(7,null) 

WITH RECURSIVE path(S,d) AS(
select t1.v1, 0 from topo t1 left outer join topo as t2 on t1.v1=t2.v2 
where t2.v2 IS null 
UNION ALL 
select distinct t1.v2, path.d + 1 from path inner join topo as t1 on 
t1.v1=path.S 
) 
select S from path group by S order by MAX(d); 

此代码给出了一个图的拓扑次序的输出。现在我想将这个输出用于另一个递归查询来查找从一个顶点到另一个顶点的路径。

我可以使用此代码生成的输出到另一个递归查询。我试图以正常的方式做到这一点,但输出显示错误。

+0

您可以通过向现有的递归CTE添加一个新字段来获得该路径吗? – JNevill

+0

如何?假设我想要从3到7的路径。这可能没有写另一个递归查询? – user3503711

回答

1

添加到您现有的递归SQL获得路径:

WITH RECURSIVE path AS(
select 
    t1.v1 as start, 
    t1.v2 as end, 
    CAST(t1.v1 as VARCHAR(30)) as path 
    0 as depth 
from topo t1 
    left outer join topo as t2 on t1.v1=t2.v2 
where t2.v2 IS null 

UNION ALL 
select 
    path.start , 
    t1.v2 as end, 
    path.path || '>' || t1.v1,  
    path.d + 1 
from path 
    inner join topo as t1 on t1.v1=path.end 
) 
SELECT * FROM path 

在一对夫妇更字段只是增加了跟踪发生了什么事,你遍历层次结构。 Start将从第一个查询中为静态。这将是每个记录1,因为这是您的出发点。 End是您当前正在工作的任何节点。 path会在找到每个新节点时连接末端节点。 depth会告诉你你走遍了多远。