我不太习惯生成复杂的 SQL 查询,并且在设计用于网络遍历的递归查询时很难将我对过程语言和基于集合的操作的理解结合起来。我希望通过对有向图进行深度优先搜索(每个节点可以有多个上游边)来找到位于特定节点“上游”的一组边,并且最好在 SQL 中实现这一点。
我想要做的伪代码如下所示:
interesting_pipes = Pipes[]
func find_all_pipes_upstream(node n)
if is_inlet(nodename)
return Nil
else
for p in upstream_pipes:
if p in interesting_pipes:
return Nil
else
interesting_pipes.append(p)
find_all_pipes_upstream(upstream_node(p))
Run Code Online (Sandbox Code Playgroud)
我已经用纯 SQL 编写了以下函数:
upstream_pipes(node_name varchar) RETURNS SETOF "Pipes"
upstream_node(pipe_name varchar) RETURNS "Node"
is_inlet(node_name) RETURNS boolean
Run Code Online (Sandbox Code Playgroud)
WITH RECURSIVE但在将上述伪代码转换为 PostgreSQL查询或 PL/pgSQL 函数时,我很难弄清楚如何管理作用域和返回类型。我见过的大多数查询示例WITH RECURSIVE都是为了遍历树而设计的,其中每个节点只有一个父节点。有没有人对如何最好地解决这个问题有任何提示/建议?
干杯,
将要