postgresql - Postgres递归json查询
问题描述
我有 2 张桌子
CREATE TABLE parent (
id SERIAL PRIMARY KEY,
label VARCHAR
);
CREATE TABLE child (
id SERIAL PRIMARY KEY,
label VARCHAR,
child_id INTEGER,
parent_id INTEGER
);
child 可以对其自身进行递归引用。我想用它的所有孩子作为 json 数组来查询父母。对于单级我有
SELECT
p.label, jsonb_agg(jsonb_build_object('id', c.id, 'label', c.label, 'child_id', c.child_id, 'parent_id', c.parent_id))
as children
FROM parent p LEFT JOIN child c on c.parent_id = p.id GROUP BY p.id
这让我
[ { id: 1,
label: 'parent 1',
children:
[ { id: 1,
label: 'child 1',
child_id: null,
parent_id: 1 },
{ id: 2,
label: 'child 2',
child_id: 1,
parent_id: 1 } ] } ]
这适用于单级,但我想要它的所有孩子,像这样
[ { id: 1,
label: 'parent 1',
children:
[ { id: 1,
label: 'child 1',
child_id: null,
parent_id: 1
children: [
{ id: 2
label: 'child 1s child'
child_id: 1,
parent_id: 1 }
] },
{ id: 3,
label: 'other child',
child_id: null,
parent_id: 1 } ] } ]
我该如何查询?
解决方案
推荐阅读
- azure-active-directory - 设置自定义属性永远不会完成
- python - 生成图像的 Z-Stack 并使用 python 创建堆叠图像的 2D 自上而下视图
- c# - 如何为 HttpWebRequest 请求设置用户属性“-u”
- c++ - 为什么 std::istream::gcount 返回比预期多一个字符
- hadoop - 输入文本文件没有标题
- perforce - 如何记录当前客户端状态并在以后重新同步
- java - 如何使用 selenium 和 java 在 Firefox 中打开一个新的空选项卡
- passport.js - 反序列化用户时遇到问题
- java - 如何有选择地跳过 Flux 上的几个处理步骤
- python - 如何组合单个订单的值?