在 PostrgreSQL 中是否有等效的 connectby 来按树上升? [英] Is there an equivalent of connectby in PostrgreSQL to go up by tree?

查看:37
本文介绍了在 PostrgreSQL 中是否有等效的 connectby 来按树上升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在 postgresql12 中使用树,并发现了一个很好的函数 connectby.

I am learning how to work with trees in postgresql12 and found a good function connectby.

例如:

SELECT * FROM connectby('descriptor_value', 'descriptor_value_id', 
    'parent_value_id', '1', 0, '->') 

给出以下输出:

但是,我不想从根开始构建所有树,我想从节点开始分支到根(性能).例如,我想作为参数传递 87 并获得 1->86->87.有这样的功能吗?

However, I don't want to build all tree starting from root, I want to get branch to root starting from node (performance). For example, I want to pass as argument 87 and get 1->86->87. Is there such a function?

推荐答案

这通常使用 递归公用表表达式.

with recursive cte as (
  select descriptor_value_id, parent_value_id, 1 as level
  from descriptor_value
  where descriptor_value_id = 87
  union all
  select p.descriptor_value_id, p.parent_value_id, c.level + 1
  from descriptor_value p 
    join cte c on c.parent_value_id = p.descriptor_value_id
)
select * 
from cte;

<小时>

connectby() 函数自 Postgres 8.4 中引入递归 CTE 以来已经过时了


The connectby() function is pretty much obsolete since the introduction of recursive CTEs in Postgres 8.4

这篇关于在 PostrgreSQL 中是否有等效的 connectby 来按树上升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆