將基/根uuid&名稱保留在遞歸循環中有助于聚合。 下面的解決方案使用EXISTS來知道遞歸何時結束。 WITH RECURSIVE RCTE_NODES AS ( SELECT uuid , name , uuid as root_uuid , name as root_name , 1 as lvl , ARRAY[]::uuid[] as children , true as has_next FROM category WHERE parent_uuid IS null UNION ALL SELECT cat.uuid , cat.name , cte.root_uuid , cte.root_name , cte.lvl+1 , cte.children || cat.uuid , (exists(select 1 from category cat2 where cat2.parent_uuid = cat.uuid)) FROM RCTE_NODES cte JOIN category cat ON cat.parent_uuid = cte.uuid)SELECT root_uuid as uuid, root_name as name, array_agg(children) as childrenFROM RCTE_NODESWHERE has_nex