postgres中的connect_by_root等价物

Neh*_*eha 2 sql oracle postgresql

如何在postgres中隐藏oracle的connect_by_root查询.例如:这是一个oracle查询.

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

a_h*_*ame 10

您将使用递归公用表表达式,它只是通过递归级别"携带"根:

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

有关手册中递归公用表表达式的更多详细信息:http://www.postgresql.org/docs/current/static/queries-with.html

  • @Neha:如果有效,请考虑[*接受*答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). (2认同)