Created
March 30, 2015 23:36
-
-
Save fritzy/1b051bffc608cd25bd1c to your computer and use it in GitHub Desktop.
generalized json joining
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fritzy=# select * from authors2; | |
id | name | |
----+-------------- | |
1 | Nathan Fritz | |
(1 row) | |
fritzy=# select * from books2; | |
id | title | author_id | |
----+-----------------------+----------- | |
1 | Happy Fun Times | 1 | |
2 | Derpin with the Stars | 1 | |
(2 rows) | |
fritzy=# select id, name, (select json_agg(row_to_json(book_r)) from (select title from books2 WHERE books2.author_id=authors2.id) book_r) AS books from authors2; | |
id | name | books | |
----+--------------+------------------------------------------------------------------ | |
1 | Nathan Fritz | [{"title":"Happy Fun Times"}, {"title":"Derpin with the Stars"}] | |
(1 row) | |
fritzy=# select id, name, (select json_agg(row_to_json(book_r)) from (select id, title from books2 WHERE books2.author_id=authors2.id) book_r) AS books from authors2; | |
id | name | books | |
----+--------------+-------------------------------------------------------------------------------- | |
1 | Nathan Fritz | [{"id":1,"title":"Happy Fun Times"}, {"id":2,"title":"Derpin with the Stars"}] | |
(1 row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment