Skip to content

Instantly share code, notes, and snippets.

@fritzy
Created March 30, 2015 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fritzy/1b051bffc608cd25bd1c to your computer and use it in GitHub Desktop.
Save fritzy/1b051bffc608cd25bd1c to your computer and use it in GitHub Desktop.
generalized json joining
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