首页 > 解决方案 > Postgres:将对象图转换为 JSON

问题描述

是否有将 Postgres 对象图转换为嵌套 JSON 树的过程?

语境:

下面的查询获取所有作者的所有书籍的所有评论:

select author.id, book.title, review.text
from author
left join book on author.id = book.author_id
left join review on book.id = review.book_id;

使用我的测试数据集,这将返回:

id  title                       text
1   Oathbringer                 obath
1   Oathbringer                 oath
1   The Way of Kings            a
1   The Way of Kings            bye
1   The Way of Kings            hi
2   The Eye of the World        w
3   The Fellowship of the Ring  x

表格格式不方便,所以我将其转换为 json:

select json_agg(sub2.*) as data from (
  select sub.id, sub.title, json_agg(sub.text) as review from (
    select author.id, book.title, review.text
    from author
    left join book on author.id = book.author_id
    left join review on book.id = review.book_id
  ) as sub group by sub.id, sub.title
) as sub2;

数据被提取为

[  
   {  
      "id":1,
      "title":"Oathbringer",
      "review":[  
         "obath",
         "oath"
      ]
   },
   {  
      "id":1,
      "title":"The Way of Kings",
      "review":[  
         "a",
         "bye",
         "hi"
      ]
   },
   {  
      "id":2,
      "title":"The Eye of the World",
      "review":[  
         "w"
      ]
   },
   {  
      "id":3,
      "title":"The Fellowship of the Ring",
      "review":[  
         "x"
      ]
   }
]

不幸的是,查询不正确,因为作者的书籍没有得到聚合。为了纠正这个问题,我写了这个查询:

select sub2.id, json_agg((sub2.title, sub2.review)) as data from (
  select sub.id, sub.title, json_agg(sub.text) as review from (
    select author.id, book.title, review.text
    from author
    left join book on author.id = book.author_id
    left join review on book.id = review.book_id
  ) as sub group by sub.id, sub.title
) as sub2 group by sub2.id;

但是json键搞砸了('f1'而不是'title','f2'而不是'review')。

问题:

标签: sqljsonpostgresql

解决方案


推荐阅读