PostgreSQL 中是否有相当于 connect by 的功能来按树向上?

2023-12-20

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

例如:

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

给出以下输出:

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


这通常是使用递归公用表表达式 https://www.postgresql.org/docs/current/queries-with.html.

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;

The connectby()自从 Postgres 8.4 中引入递归 CTE 以来,该函数几乎已经过时了

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PostgreSQL 中是否有相当于 connect by 的功能来按树向上? 的相关文章

随机推荐