sql - 将 Oracle CONNECT BY 迁移到 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 中的第一个查询与start with
Oracle 的start with
. 第二个查询中返回到 CTE 的 JOIN 与connect by
Oracle 查询中的部分相匹配。
推荐阅读
- java - 协议处理程序启动失败 Spring Boot SSL 应用程序
- vb.net - 使用 Twitter 开发人员 API 在 VB.Net 中对 HttpWebRequest 的 400 错误请求
- c++ - 如何使用 TSS.MSR (C++) 导入椭圆 p256 公钥
- cloud-foundry - 是否可以使用 Cloud Foundry 任务调度程序覆盖磁盘空间和内存设置?
- android - android webrtc无法使用coturn服务器在LTE hostspot和wifi之间连接
- c# - 使用 TCP 的 C# 服务器-客户端实现
- javascript - 当道具在同一组件中更新时如何运行函数?
- python - 如何正则表达式句子的开头和结尾 - python
- regex - SAS:任何语言中单词字符的正则表达式
- django - 为什么 Heroku 不阅读我的 Django urls.py?