【问题标题】:Postgres nested JSON array using row_to_jsonPostgres 使用 row_to_json 嵌套 JSON 数组
【发布时间】:2014-01-15 12:18:10
【问题描述】:

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

我有 2 个表 journal 和 journaldetail。

架构是 -

期刊 : journalid, totalamount

journaldetail : journaldetailid, journalidfk, account, amount

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

我想要以下格式的输出:

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

但是,通过按照 post 编写此查询,查询是:

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 
   }
}

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

【问题讨论】:

    标签: json postgresql-9.2


    【解决方案1】:

    我从here找到了答案:

    这里是查询:

    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
    

    这给出了数组格式的输出。

    【讨论】:

    • 我这仍然是 PostgreSQL 12+ 的最佳方法吗?
    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 2012-10-24
    • 2021-04-17
    • 1970-01-01
    • 2017-11-12
    • 2017-02-27
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多