gpt4 book ai didi

sql - 将 Oracle CONNECT BY 迁移到 postgresql 10

转载 作者:行者123 更新时间:2023-11-29 12:07:00 26 4
gpt4 key购买 nike

我有这个 SQL:

SELECT count(*) as ct
FROM classifications cls
WHERE
cls.classification_id = :classification_id
START WITH cls.classification_id = :root_classification_id
CONNECT BY NOCYCLE PRIOR cls.classification_id = cls.parent_id

并且需要将它迁移到 postgresql 10。

我已经安装了扩展 tablefunc 并尝试使用 connectedby。这是我的尝试:

SELECT count(*) as ct
FROM classifications cls
WHERE
cls.classification_id = :classification_id

union
SELECT count(classification_id) FROM connectby('classifications','classification_id','parent_id',:root_classification_id,5)
as t(classification_id varchar, parent_id varchar,level int)

问题是并集的方式是错误的,因为那样你会得到 2 个计数结果。

最佳答案

无需使用 tablefunc 扩展。这可以使用 recursive CTE 轻松完成。

with recursive tree as (

select cls.classification_id, cls.parent_id
from classifications cls
where cls.classification_id = :root_classification_id

union all

select child.classification_id, child.parent_id
from classifications child
join tree parent on child.parent_id = parent.classification_id
)
select count(*)
from tree;

CTE 中的第一个查询匹配来自 Oracle 的 start withstart with 部分。第二个查询中返回 CTE 的 JOIN 匹配 Oracle 查询中的 connect by 部分。

关于sql - 将 Oracle CONNECT BY 迁移到 postgresql 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com