【发布时间】: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
【问题讨论】:
-
我认为您需要对
authors和tags进行子选择。你能用数据示例准备一个db-fiddle吗?如果你这样做,你会更快地得到答案。
标签: sql json postgresql