gpt4 book ai didi

json - 从 Postgres 和 jOOQ 中的分层表递归生成 JSON 树

转载 作者:行者123 更新时间:2023-12-05 04:51:57 28 4
gpt4 key购买 nike

我在 Postgres 数据库中有一个分层表,例如category .结构很简单,如下所示:

<表类="s-表"><头>idparent_id名字<正文>1空一个2空B31A143A1a53A1b62B172B2

我需要从这个表中得到的是像这样的递归深树结构:

[
{
"id": 1,
"name": "A",
"children": [
{
"id": 3,
"name": "A1",
"children": [
{
"id": 4,
"name": "A1a",
"children": []
},
{
"id": 5,
"name": "A1b",
"children": []
}
]
}
]
},
{
"id": 2,
"name": "B",
"children": [
{
"id": 6,
"name": "B1",
"children": []
},
{
"id": 7,
"name": "B2",
"children": []
}
]
},
]

是否有可能使用 WITH RECURSIVE 的组合使用未知深度和 json_build_array()还是其他一些解决方案?

最佳答案

我在 this excellent blog post here 中找到了这个问题的答案,因为我想知道如何在 jOOQ 中概括这个问题。如果 jOOQ 能够以通用方式具体化任意递归对象树,那将会很有用:https://github.com/jOOQ/jOOQ/issues/12341

与此同时,使用受上述博文启发并进行一些修改的 SQL 语句。如果必须,请转换为 jOOQ,尽管您也可以将其存储为 View :

WITH RECURSIVE
d1 (id, parent_id, name) as (
values
(1, null, 'A'),
(2, null, 'B'),
(3, 1, 'A1'),
(4, 3, 'A1a'),
(5, 3, 'A1b'),
(6, 2, 'B1'),
(7, 2, 'B2')
),
d2 AS (
SELECT d1.*, 0 AS level
FROM d1
WHERE parent_id IS NULL
UNION ALL
SELECT d1.*, d2.level + 1
FROM d1
JOIN d2 ON d2.id = d1.parent_id
),
d3 AS (
SELECT d2.*, jsonb_build_array() children
FROM d2
WHERE level = (SELECT max(level) FROM d2)
UNION (
SELECT (branch_parent).*, jsonb_agg(branch_child)
FROM (
SELECT
branch_parent,
to_jsonb(branch_child) - 'level' - 'parent_id' AS branch_child
FROM d2 branch_parent
JOIN d3 branch_child ON branch_child.parent_id = branch_parent.id
) branch
GROUP BY branch.branch_parent
UNION
SELECT d2.*, jsonb_build_array()
FROM d2
WHERE d2.id NOT IN (
SELECT parent_id FROM d2 WHERE parent_id IS NOT NULL
)
)
)
SELECT jsonb_pretty(jsonb_agg(to_jsonb(d3) - 'level' - 'parent_id')) AS tree
FROM d3
WHERE level = 0;

dbfiddle .再次阅读 linked blog post解释这是如何工作的

关于json - 从 Postgres 和 jOOQ 中的分层表递归生成 JSON 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66656005/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com