小编Ben*_*Ben的帖子

从递归树结构创建 JSON 对象

具有这种简单的多对多自引用结构。
一个项目通过表拥有其他项目joins

CREATE TABLE items (
  item_id   serial PRIMARY KEY
, title     text
);

CREATE TABLE joins (
  id        serial PRIMARY KEY
, item_id   int
, child_id  int
);

INSERT INTO items (item_id, title) VALUES
  (1, 'PARENT')
, (2, 'LEVEL 2')
, (3, 'LEVEL 3.1')
, (4, 'LEVEL 4.1')
, (5, 'LEVEL 4.2')
, (6, 'LEVEL 3.2')
;

INSERT INTO joins (item_id, child_id) VALUES
  (1, 2)
, (2, 3)
, (3, 4)
, (3, 5)
, (2, 6) …
Run Code Online (Sandbox Code Playgroud)

postgresql tree cte json recursive

5
推荐指数
1
解决办法
7183
查看次数

标签 统计

cte ×1

json ×1

postgresql ×1

recursive ×1

tree ×1