I have a few tables with a foreign key relationship.
books
| 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) |
I want JSON output something like this:
{
"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
}
]
}
I don't necessarily need that books root-level object if it's too difficult to include. I can probably just deal with the array itself.
I have no clue how to do this. I've started out with something like this:
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
authorsandtags. Can you prepare a db-fiddle with example of data? You will get an answer much faster if you do that.