Search code examples
postgresqljoinmergejsonb

Is it achievable to merge nested JSONB fields with a JOIN-like statement in PostgreSQL?


Given this tables:

BOOKS

 id | data
----+-------------------------------------------------------
 1  | { title: 'Book 1', price: 10.5, author: { id: 2 } }
 2  | { title: 'Book 2', price: 11.5, author: { id: 2 } }

AUTHORS

 id | data
-----+-------------------------------------------------------
 1  | { name: 'Author 1', address: 'Address author 1' }
 2  | { name: 'Author 2', address: 'Address author 2' }

Is it possible to obtain this result, by merging the author key, with a JOIN-like statement or using jsonb functions?

BOOKS QUERY RESULT

 id | data
----+------------------------------------------------------------------------------------------------------
 1  | { title: 'Book 1', price: 10.5, author: { id: 2, name: 'Author 2', address: 'Address author 2'} }
 2  | { title: 'Book 2', price: 11.5, author: { id: 2, name: 'Author 2', address: 'Address author 2'} }

Thanks


Solution

  • select b.data || jsonb_build_object('author', b.data->'author' || a.data)
    from books b
    join authors a on a.id = (b.data->'author'->>'id')::int;
    

    SqlFiddle