我有这样一个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并需要将其迁移到PostgreSQL10。
我已经安装了扩展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个结果。
发布于 2019-10-18 15:42:46
不需要使用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中的第一个查询与甲骨文的start with中的start with部件匹配。并且第二个查询中返回到CTE的联接与Oracle查询中的connect by部件相匹配。
https://stackoverflow.com/questions/58446048
复制相似问题