Recursive query challenge - simple parent/child example

前端 未结 3 1037
灰色年华
灰色年华 2020-12-28 21:05

Note: with help from RhodiumToad on #postgresql, I\'ve arrived at a solution, which I posted as answer. If anyone can improve on this, please chime in!

I have not be

3条回答
  •  余生分开走
    2020-12-28 21:23

    With help from RhodiumToad on #postgresql, I've arrived at this solution:

    WITH RECURSIVE node_graph AS (
        SELECT ancestor_node_id as path_start, descendant_node_id as path_end,
               array[ancestor_node_id, descendant_node_id] as path 
        FROM node_relations
    
        UNION ALL 
    
        SELECT ng.path_start, nr.descendant_node_id as path_end,
               ng.path || nr.descendant_node_id as path
        FROM node_graph ng
        JOIN node_relations nr ON ng.path_end = nr.ancestor_node_id
    ) 
    SELECT * from node_graph order by path_start, array_length(path,1);
    

    The result is exactly as expected.

提交回复
热议问题