Last active
August 29, 2015 14:17
-
-
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.
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 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