Question

J'ai une requête Oracle avec un NOCYCLE clause que je dois traduire en 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 

J'ai converti celui-ci à l'aide de la question et de la réponse danséquivalent connect_by_root dans postgres

comme

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

mais en cela il n'y a aucune clause pour NOCYCLE si le parent est également l'un des enfants, cette requête renverra une erreur.

Était-ce utile?

La solution

Vous pouvez collecter les identifiants pour chaque niveau puis rejoindre à condition que l'identifiant "actuel" ne soit pas contenu dans le chemin :

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top