Postgres中的诺斯
-
21-12-2019 - |
题
我有一个使用NOCYCLE
子句的Oracle查询,我必须转换为postgres:
SELECT FG_ID,CONNECT_BY_ROOT FG_ID as Parent_ID
FROM FG t
START WITH t.Parent_filter_group_id is null
CONNECT BY NOCYCLE PRIOR t.FILTER_GROUP_ID = t.PARENT_FILTER_GROUP_ID
.
我在问题的帮助下转换了这一个并回答 connect_by_root在postgres
中相同
with recursive fg_tree as (
select FG_ID,
FG_ID as fg
from FG
where Parent_filter_group_id is null
union all
select c.FG_ID,
p.fg
from FG c join fg_tree p on p.FG_ID = PARENT_FILTER_GROUP_ID
)
select * from fg_tree
order by FG_ID
.
但在此情况下,如果父父片也是一个子父母,那么该查询将返回错误。
解决方案
您可以收集每个级别的ID,然后加入“当前”ID不包含在路径中的条件:
with recursive fg_tree as (
select FG_ID,
FG_ID as fg,
array[fg_id] as path
from FG
where Parent_filter_group_id is null
union all
select c.FG_ID,
p.fg,
p.fg||c.fg_id
from FG c
join fg_tree p on p.FG_ID and c.fg_id <> ALL (p.path)
)
select fg_id, fg
from fg_tree
order by filter_group_id
. 不隶属于 StackOverflow