从树状结构中获取所有子节点(邻接列表模型)

CREATE OR REPLACE FUNCTION get_categories_all_children(use_parent INT4) RETURNS INT4[] AS $$
DECLARE
    process_parents INT4
[] := ARRAY[ use_parent ];
    children INT4
[] := '{}';
    new_children INT4
[];
BEGIN
    
WHILE ( array_upper( process_parents, 1 ) IS NOT NULL ) LOOP
        new_children :
= ARRAY( SELECT id FROM categories WHERE parent_id = ANY( process_parents ) AND id <> ALL( children ) );
        children :
= children || new_children;
        process_parents :
= new_children;
    
END LOOP;
    
RETURN children;
END;
$$ LANGUAGE plpgsql;


原文地址:https://www.cnblogs.com/javaite/p/1641211.html