Skip to content

Instantly share code, notes, and snippets.

@fritzy
Last active August 29, 2015 14:17
Show Gist options
  • Save fritzy/b6867e2621b748fee384 to your computer and use it in GitHub Desktop.
Save fritzy/b6867e2621b748fee384 to your computer and use it in GitHub Desktop.
I've been playing around with JSON(B) columns in Postgres 9.4. I haven't found a great way to join from one value into another (without crazy JSON reconstruction), but this is close.
fritzy=# select * from authors;
id | value
----+--------------------------
1 | {"name": "Nathan Fritz"}
(1 row)
fritzy=# select * from books;
id | value
----+----------------------------------------------------
1 | {"title": "Ham, and Eating It", "author": 1}
2 | {"title": "Learn How To Read Gooder", "author": 1}
(2 rows)
fritzy=# select value author, (select json_agg(value) from books where authors.id=(value->'author')::text::int) books from authors;
author | books
--------------------------+----------------------------------------------------------------------------------------------------
{"name": "Nathan Fritz"} | [{"title": "Ham, and Eating It", "author": 1}, {"title": "Learn How To Read Gooder", "author": 1}]
(1 row)
fritzy=# select json_build_object('author', value, 'books', (select json_agg(value) from books where authors.id::text=(value->'author')::text)) books from authors;
books
-----------------------------------------------------------------------------------------------------------------------------------------------------
{"author" : {"name": "Nathan Fritz"}, "books" : [{"title": "Ham, and Eating It", "author": 1}, {"title": "Learn How To Read Gooder", "author": 1}]}
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment