递归查询来模拟PostgreSQL中的文件夹结构

qxsslcnc  于 10个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(96)

我试图用这个表来模拟PostgreSQL中的一个简单的文件夹结构:

CREATE TABLE folders (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
    name text,
    parent UUID REFERENCES folders(id)
);

字符串
我有一些简单的数据(ID简化):

(1, "parent", NULL)
(2, "child of 1", 1)
(3, "child of 2", 2)
(4, "other parent", NULL)


我使用以前的一些帖子创建了这个递归查询:

WITH RECURSIVE recursive_cte AS (
    SELECT id, name, parent
    FROM folders
    WHERE parent IS NULL -- Start with the root items (where parent is NULL)
    
    UNION ALL
    
    SELECT f.id, f.name, f.parent
    FROM folders f
    JOIN recursive_cte rc ON f.parent = rc.id
)
SELECT id, name, 
  (
      SELECT json_agg(json_build_object('id', c.id, 'name', c.name))
      FROM recursive_cte c
      WHERE c.parent = folders.id
  ) AS children
FROM folders
WHERE parent IS NULL;


返回的数据是:

id, name, children[]
(1, "parent", [{"id":2, "name":"child of 1"}])
(4, "other parent", [])


修改我的查询需要什么步骤,这样我就可以递归地构建“children”列,让json也包含任何查尔兹?

vfwfrxfs

vfwfrxfs1#

WITH RECURSIVE recursive_cte AS (
    SELECT id, name, parent, jsonb_build_object('id', id, 'name', name) AS json_data
    FROM folders
    WHERE parent IS NULL -- Start with the root items (where parent is NULL)

    UNION ALL

    SELECT f.id, f.name, f.parent, jsonb_build_object('id', f.id, 'name', f.name) || rc.json_data
    FROM folders f
    JOIN recursive_cte rc ON f.parent = rc.id
)
SELECT id, name, jsonb_agg(json_data) AS children
FROM recursive_cte
GROUP BY id, name
ORDER BY id;

字符串
使用jsonb_build_object函数为递归公共表表达式中的每个文件夹创建JSON对象,此JSON对象包括文件夹的“id”和“name”,然后使用||操作符将当前文件夹的JSON数据与递归CTE中其父文件夹的JSON数据连接起来;在JSON结构中构建层次结构。

相关问题