簡體   English   中英

帶連接的 Postgres JSON 數組?

[英]Postgres JSON array with join?

我有幾個具有外鍵關系的表。

圖書

柱子 類型
ID 整數4
標題 varchar(200)
... ...

book_authors

柱子 類型
ID 整數4
名稱 變量字符(50)
網址 varchar(200)

book_authors_lookup

柱子 類型
書號 整數4
作者_id 整數4

book_tags

柱子 類型
ID 整數4
書號 整數4
名稱 變量字符(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

我建議像這樣“編織”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;

請。 請注意,上述腳本尚未經過測試,因此可能存在一些小錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM