【发布时间】:2014-10-01 09:43:48
【问题描述】:
我的 PostgreSQL 数据库中有一个有向图,节点和循环之间可以有多个路径:
create table "edges" ("from" int, "to" int);
insert into "edges" values (0, 1), (1, 2), (2, 3), (3, 4), (1, 3);
insert into "edges" values (10, 11), (11, 12), (12, 11);
我想找出一个节点和连接到它的每个节点之间的最小边数:
with recursive "nodes" ("node", "depth") as (
select 0, 0
union
select "to", "depth" + 1
from "edges", "nodes"
where "from" = "node"
) select * from "nodes";
返回所有路径的深度:
node 0 1 2 3 3 4 4
depth 0 1 2 2 3 3 4
0 -> 1 -> 2 -> 3 -> 4
0 -> 1 ------> 3 -> 4
我需要最低限度,但是 递归查询的递归项中不允许使用聚合函数
with recursive "nodes" ("node", "depth") as (
select 0, 0
union
select "to", min("depth") + 1
from "edges", "nodes"
where "from" = "node"
group by "to"
) select * from "nodes";
在结果上使用聚合函数虽然有效:
with recursive "nodes" ("node", "depth") as (
select 0, 0
union all
select "to", "depth" + 1
from "edges", "nodes"
where "from" = "node"
) select * from (select "node", min("depth")
from "nodes" group by "node") as n;
按预期返回
node 0 1 2 3 4
depth 0 1 2 2 3
但是,进入循环会导致无限循环,对查询“节点”的递归引用不得出现在子查询中,因此我无法检查节点是否已被访问:
with recursive "nodes" ("node", "depth") as (
select 10, 0
union
select "to", "depth" + 1
from "edges", "nodes"
where "from" = "node"
and "to" not in (select "node" from "nodes")
) select * from "nodes";
我在这里寻找的结果是
node 10 11 12
depth 0 1 2
有没有办法通过递归查询/公用表表达式来做到这一点?
另一种方法是创建一个临时表,迭代地添加行直到用尽;即呼吸优先搜索。
相关:this answer 检查节点是否已经包含在路径中并避免循环,但仍然无法避免做不必要的工作来检查比已知最短路径更长的路径,因为它仍然表现得像深度优先搜索
【问题讨论】:
标签: sql postgresql common-table-expression