Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connect_by_root equivalent in postgres

How I can covert connect_by_root query of oracle in postgres. ex: This is an oracle query.

select fg_id, connect_by_root fg_id as fg_classifier_id
from fg
start with parent_fg_id is null
connect by prior fg_id = parent_fg_id 
like image 575
Neha Avatar asked Dec 11 '22 07:12

Neha


1 Answers

You would use a recursive common table expression that simply "carries" the root through the recursion levels:

with recursive fg_tree as (
  select fg_id, 
         fg_id as fg_clasifier_id -- <<< this is the "root" 
  from fg
  where parent_fg_id is null -- <<< this is the "start with" part
  union all
  select c.fg_id, 
         p.fg_clasifier_id
  from fg c 
    join fg_tree p on p.fg_id = c.parent_fg_id -- <<< this is the "connect by" part
) 
select *
from fg_tree;

More details on recursive common table expressions in the manual: http://www.postgresql.org/docs/current/static/queries-with.html

like image 77
a_horse_with_no_name Avatar answered Dec 27 '22 10:12

a_horse_with_no_name