【问题标题】:Postgres JSON array with join?带有连接的 Postgres JSON 数组?
【发布时间】:2021-07-30 05:31:23
【问题描述】:

我有几个具有外键关系的表。

书籍

Column Type
id int4
title varchar(200)
... ...

book_authors

Column Type
id int4
name varchar(50)
url varchar(200)

book_authors_lookup

Column Type
book_id int4
author_id int4

book_tags

Column Type
id int4
book_id int4
name varchar(50)

我想要这样的 JSON 输出:

{
  "books": [
    {
      "book_id": 1,
      "title": "Book 1 Title",
      "authors": [
        {"name": "John Doe", "url": "http://twitter/@johndoe"},
        {"name": "Jane Doe", "url": "http://twitter/@janedoe"}
      ],
      "tags": ["tag1", "tag2"]
    },
    {
      // Next book
    }
  ]
}

如果太难包含,我不一定需要那个 books 根级对象。我可能只处理数组本身。

我不知道该怎么做。我已经开始了这样的事情:

select json_build_object(
  'book_id', b.id,
  'title', b.title,
  'authors', json_build_array(??)
  'tags', json_build_array(??)
)
from books b
join book_tags bt on bt.book_id = b.id
join book_authors_lookup bal on bal.book_id = b.id
join book_authors ba on ba.id = bal.author_id

【问题讨论】:

  • 我认为您需要对 authorstags 进行子选择。你能用数据示例准备一个db-fiddle吗?如果你这样做,你会更快地得到答案。

标签: sql json postgresql


【解决方案1】:

我建议像这样“编织” JSON 结构。

with t as
(
 select 
    b.id as book_id, 
    b.title, 
    (
        select jsonb_agg(jsonb_build_object('name', ba.name, 'url', ba.url)) 
        from book_authors ba 
        inner join book_authors_lookup bal on ba.id = bal.author_id 
        where bal.book_id = b.id
    ) as authors,
    (
        select array_agg(bt.name)
        from book_tags bt
        where bt.book_id = b.id
    ) as tags
 from books b    
)
select jsonb_build_object('books', jsonb_agg(to_json(t.*))) from t;

请。请注意,上述脚本尚未经过测试,因此可能存在一些小错误。

【讨论】:

  • 哇,谢谢!我唯一需要改变的是删除引号:ba.'url'ba.url。完美运行!
  • 复制/粘贴:)。也修好了。
猜你喜欢
  • 2017-11-30
  • 1970-01-01
  • 2021-03-19
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
相关资源
最近更新 更多