PostgreSQL – 从包含路径的表生成JSON树对象

给定一个表,其中包含未知的树结构的路径/节点:

| id | path_id | node
| 1  | p1      | n1
| 2  | p1      | n2
| 3  | p1      | n3
| 4  | p2      | n1
| 5  | p2      | n2
| 6  | p2      | n4

相应的树结构将是

    n1 
   /  
  n2
 /  \
n3   n4

是否可以使用SQL和PostgreSQL函数为此树生成JSON对象?

最佳答案 好像你有一个路径列表,其中部分重叠.

首先删除重复边:

SELECT DISTINCT  node
               , lag(node) OVER (PARTITION BY path_id ORDER BY id) AS parent
FROM   tbl
ORDER  BY parent NULLS FIRST, node;  -- ORDER BY optional

父节点为根节点为NULL.您可能希望从结果中删除此“非边缘”.
然后,要为此树生成JSON对象,您可以使用json_agg()

SELECT json_agg(sub) AS array_of_edges
FROM  (
   SELECT DISTINCT node
                 , lag(node) OVER (PARTITION BY path_id ORDER BY id) AS parent
   FROM   tbl
   ORDER  BY parent NULLS FIRST, node  -- ORDER BY optional
   ) sub;

SQL Fiddle.

点赞