我存盤了一棵包含多個節點的樹。該表中的每條記錄都代表一個節點及其父節點,如下所示:
| 節點編號 | parent_id |
|---|---|
| 一個 | 無效的 |
| 乙 | 一個 |
| C | 一個 |
| 丁 | 乙 |
| 乙 | 乙 |
結果,可視化樹將如下所示:樹節點
我的目標是創建一個函式來保存樹中每個葉子的 JSON 路徑。因此,對于我當前的表,結果應如下所示:
| 葉子_id | json_path |
|---|---|
| C | {“名字”:“A”,“孩子”:[{“名字”:“C”,“孩子”:[]}]} |
| 丁 | {“名字”:“A”,“孩子”:[{“名字”:“B”,“孩子”:[{“名字”:“D”,“孩子”:[]}]}]} |
| 乙 | {“名字”:“A”,“孩子”:[{“名字”:“B”,“孩子”:[{“名字”:“E”,“孩子”:[]}]}]} |
已經有一個函式執行我要實作的格式的問題(下面的鏈接): nested-json-object。但是,寫入的函式選擇了整棵樹。因此,正如我上面提到的,我需要每個葉節點的路徑。
uj5u.com熱心網友回復:
使用遞回cte:
with recursive cte(id, l, js) as (
select t.node_id, t.node_id, jsonb_build_object('name', t.node_id, 'children', '[]'::jsonb) from tbl t
where not exists (select 1 from tbl t1 where t1.parent_id = t.node_id)
union all
select t3.parent_id, t3.l, jsonb_build_object('name', t3.parent_id, 'children', t3.js)
from (select t2.parent_id, t2.l, jsonb_agg(t2.js) js
from (select t1.parent_id, c.l, c.js from tbl t1
join cte c on c.id = t1.node_id) t2 group by t2.parent_id, t2.l) t3
)
select l leaf_id, v json_path from cte
cross join jsonb_array_elements(js -> 'children') v where id is null
見小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535300.html
上一篇:處理客戶端和服務器之間的時區
