使用row_to_json的Postgres嵌套JSON数组 [英] Postgres nested JSON array using row_to_json

查看:257
本文介绍了使用row_to_json的Postgres嵌套JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用2个表创建嵌套的json数组。

I am trying to create nested json array using 2 tables.

我有2个表journal和journaldetail。

I have 2 tables journal and journaldetail.

模式为-

期刊:日记ID,总量

journaldetail:journaldetailid,journalidfk,帐户,金额

journal和journaldetail之间的关系是一对多的。

Relation between journal and journaldetail is one-to-many.

我希望以以下格式输出:

I want the output in following format :

{  journalid : 1,
totalamount : 1000,
journaldetails : [ 
   {
      journaldetailid : j1,
      account : "abc",
      amount : 500 
   },
   {
      journaldetailid : j2,
      account : "def",
      amount : 500 
   }
]}

但是,通过按照以下发布,查询为:

However, by writing this query as per this post the query is:

select j.*, row_to_json(jd) as journal from journal j
inner join (
  select * from journaldetail
) jd on jd.sjournalidfk = j.sjournalid

,输出结果如下:

{  journalid : 1,
totalamount : 1000,
journaldetails : 
   {
      journaldetailid : j1,
      account : "abc",
      amount : 500 
   }
}
{  journalid : 1,
totalamount : 1000,
journaldetails : 
   {
      journaldetailid : j2,
      account : "def",
      amount : 500 
   }
}

我希望子表数据作为父表中的嵌套数组。

I want the child table data as nested array in the parent.

推荐答案

我从此处

以下是查询:

select row_to_json(t)
from (
  select sjournalid,
    (
      select array_to_json(array_agg(row_to_json(jd)))
      from (
        select sjournaldetailid, saccountidfk
        from btjournaldetail
        where j.sjournalid = sjournalidfk        
      ) jd
    ) as journaldetail
  from btjournal j
) as t

数组格式。

这篇关于使用row_to_json的Postgres嵌套JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆