You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PG12 如何将关联查询结果返回为嵌套层级结构的JSON数据?

PostgreSQL 12 层级JSON返回调整方案

原来的函数直接关联两张表返回扁平化结果,没有做层级聚合,你可以通过PostgreSQL内置的JSON构造+聚合函数调整,以下是可直接使用的修改后函数:

方案1:子查询关联写法(逻辑更直观)

create or replace function jorder() returns json as $$
select json_agg(
    json_build_object(
        'orderid', od.orderid,
        'grandtotal', od.grandtotal,
        'details', (
            -- 聚合当前订单对应的所有明细为JSON数组
            select json_agg(
                json_build_object(
                    'detailid', ds.detailid,
                    'description', ds.description
                )
            ) from odetails ds where ds.orderid = od.orderid
        )
    )
) from orders od;
$$ language sql stable;

方案2:分组关联写法(大数据量下性能更优)

create or replace function jorder() returns json as $$
select json_agg(
    json_build_object(
        'orderid', od.orderid,
        'grandtotal', od.grandtotal,
        'details', ds.detail_list
    )
) from orders od
-- 先聚合所有明细按订单分组
join (
    select 
        orderid, 
        json_agg(json_build_object('detailid', detailid, 'description', description)) as detail_list
    from odetails
    group by orderid
) ds on od.orderid = ds.orderid;
$$ language sql stable;

核心逻辑说明

  • json_build_object:手动指定键名和对应字段值构造JSON对象,保证输出结构完全匹配需求
  • json_agg:将多行结果聚合为JSON数组,分别用来生成单订单下的details明细数组,和外层的订单列表数组
  • 两种方案返回的结果完全符合你需要的层级结构,不需要额外做数据转换

内容的提问来源于stack exchange,提问作者Jeb50

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:57:01