![](/img/trans.png)
[英]Migrate query with START WITH and CONNECT BY PRIOR from oracle to postgresql
[英]Migrate Oracle CONNECT BY to postgresql 10
我有这个 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 扩展。 这可以使用递归 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 with
start with
部分匹配。 第二个查询中返回到 CTE 的 JOIN 与 Oracle 查询中的connect by
部分相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.