我有一些数据:
rank_ | data | parent_rank
--------------------------
1 | a | NULL
2 | b | 1
3 | c | 2
4 | d | 2
5 | e | NULL
6 | f | NULL
7 | g | 6
8 | h | 6
我想转换为嵌套形式:
rank_ | nested
--------------------------------------------------------------------------------------
1 | {"D": "a", "C": [{"C": [{"C": [], "D": "c"}, {"C": [], "D": "d"}], "D": "b"}]}
5 | {"D": "e", "C": []}
6 | {"D": "f", "C": [{"C": [], "D": "g"}, {"C": [], "D": "h"}]}
其中“C”是儿童,“D”是数据.
到目前为止,我有以下代码,但我到目前为止无法将其嵌套到任意深度:https://www.db-fiddle.com/f/g7RFZQRX5JrzaYPXs62BNe/0
最佳答案 我们知道我们有数据表o:
create table o (rank_ int, data varchar(10), parent_rank int) ;
insert into o (VALUES
(1, 'a', NULL),
(2, 'b', 1),
(3, 'c', 2),
(4, 'd', 2),
(5, 'e', NULL),
(6, 'f', NULL),
(7, 'g', 6),
(8, 'h', 6)
);
然后,您可以编写一个简单的递归函数,如:
CREATE FUNCTION C(r INT) RETURNS JSONB AS
' BEGIN
return (
jsonb_build_object(
''D'', ( select
o.data
from o
where o.rank_=r),
''C'', ( select
coalesce(
array_to_json(array_agg( C(o.rank_)
ORDER BY o.rank_))::JSONB,
''[]''::JSONB )
from o
where o.parent_rank=r)
)
);
END
'
LANGUAGE plpgsql;
并调用root注释函数:
SELECT o.rank_, c(o.rank_)
from o
where o.parent_rank is null
1 {"C":[{"C":[{"C":[],"D":"c"},{"C":[],"D":"d"}],"D":"b"}],"D":"a"}
5 {"C":[],"D":"e"}
6 {"C":[{"C":[],"D":"g"},{"C":[],"D":"h"}],"D":"f"}