多对多表组合成数组

Many to many tables combine in arrays

我如何SELECT以这种格式预订:

{
   title: 'Avengers', 
   description:'Good book', 
   tags: [{id:1, name: 'Drama'},{id:2, name: 'Horror'}]
   authors: [{id:1, name: 'Alex'},{id:2, name: 'Tanya'}]
}

具有多对多关系的 tables:

或者制作 3 个不同的 pool.requests?

书籍

|id|title     |description|
|1 |'Avengers'|'Good book'|
|2 |'Fear'    |'Scary'

作者

|id|name
|1 |'Alex'
|2 |'Tanya'

authors_books

|book_id|author_id
|1      |1
|1      |2
|2      |1

标签

|id|name
|1 |'Drama'
|2 |'Horror'

tags_books

|book_id|tag_id
|1      |1
|1      |2
|2      |1

我以前在没有作者的情况下使用过这个table:

SELECT b.title, b.id, b.description,
 json_agg(json_build_object('id', t.id, 'name', t.name, 'description', 
 t.description, 'likes', tb.likes) ORDER BY tb.likes DESC) AS tags
 FROM books AS b
 INNER JOIN tags_books AS tb ON (b.id = tb.book_id)
 INNER JOIN tags AS t ON (tb.tag_id = t.id)
 WHERE b.id = 
 GROUP BY b.id;`

但是对于 table autor 的新 INNER JOIN 将会有重复值。

您应该在单独的派生表(FROM 子句中的子查询)中聚合数据(authorstags):

select 
    b.title, 
    b.description,
    t.tags, 
    a.authors
from books as b
join (
    select 
        tb.book_id,
        json_agg(json_build_object('id', t.id, 'name', t.name) order by tb.likes desc) as tags
    from tags_books as tb
    join tags as t on tb.tag_id = t.id
    group by tb.book_id
    ) t on b.id = t.book_id
join (
    select 
        ab.book_id,
        json_agg(json_build_object('id', a.id, 'name', a.name) order by ab.author_id) as authors
    from authors_books as ab
    join authors as a on ab.author_id = a.id
    group by ab.book_id
    ) a on b.id = a.book_id

  title   | description |                             tags                              |                           authors                           
----------+-------------+---------------------------------------------------------------+-------------------------------------------------------------
 Avengers | Good book   | [{"id" : 2, "name" : "Horror"}, {"id" : 1, "name" : "Drama"}] | [{"id" : 1, "name" : "Alex"}, {"id" : 2, "name" : "Tanya"}]
 Fear     | Scary       | [{"id" : 1, "name" : "Drama"}]                                | [{"id" : 1, "name" : "Alex"}]
(2 rows)