Postgres中的NOCYCLE

Sar*_*hAk 1 sql oracle postgresql connect-by

我有一个带有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 
Run Code Online (Sandbox Code Playgroud)

我已经在postgres中的connect_by_root等效问题和答案的帮助下转换了这个

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
Run Code Online (Sandbox Code Playgroud)

但是在这里没有子句,NOCYCLE如果父亲也是其中一个孩子,那么这个查询将返回错误.

a_h*_*ame 5

您可以收集每个级别的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
Run Code Online (Sandbox Code Playgroud)