How to convert oracle hierarchical queries to postgresql?

前端 未结 1 1640
无人共我
无人共我 2021-01-20 16:39

I want to convert below mentioned oracle hierarchical query to postgresql

SELECT catalog_id, sub_tree_id
FROM   my_catalog
CONNECT BY PRIOR catalog_id = sub_         


        
相关标签:
1条回答
  • 2021-01-20 17:23

    In PostgreSQL recursive queries are constructed by first specifying the initial set of rows (the non-recursive term, i.e. those at the root or final level of the hierarchy). Subsequent iterations (over the recursive term, the sub-query after the UNION ALL) then add rows to the result set from the remaining rows in the input row set until no more rows are added.

    In your case, the initial sub-query is unfiltered so you simply add all rows on the initial run, leaving nothing for subsequent runs.

    Try the following:

    WITH RECURSIVE q AS (
      SELECT po.catalog_id,po.sub_tree_id
      FROM my_catalog po
      WHERE sub_tree_id = 0  -- this initially selects only "root" rows
    UNION ALL
      SELECT po.catalog_id,po.sub_tree_id
      FROM my_catalog po
      JOIN q ON q.catalog_id=po.sub_tree_id
    )
    SELECT * FROM q;
    
    0 讨论(0)
提交回复
热议问题