鉴于此表:
图书
id | data
----+-------------------------------------------------------
1 | { title: 'Book 1', price: 10.5, authors: [{ id: 1}, { id: 2 }]}
2 | { title: 'Book 2', price: 11.5, authors: [{ id: 2 } }
AUTHORS
id | data
-----+-------------------------------------------------------
1 | { name: 'Author 1', address: 'Address author 1' }
2 | { name: 'Author 2', address: 'Address author 2' }
是否可以通过将authors键数组元素与类似JOIN的语句或使用jsonb函数合并来获得此结果?
预订查询结果
id | data
----+------------------------------------------------------------------------------------------------------
1 | { title: 'Book 1', price: 10.5, authors: [{ id: 1, name: 'Author 1', address: 'Address author 1' }, { id: 2, name: 'Author 2', address: 'Address author 2'}] }
2 | { title: 'Book 2', price: 11.5, authors: [{ id: 2, name: 'Author 2', address: 'Address author 2'}] }
由于
答案 0 :(得分:0)
select b.data || jsonb_build_object('authors', jsonb_agg(a.data ||
jsonb_build_object('id', a.id)))
from books b
left join (select id, jsonb_array_elements(data->'authors') from books) ba on
ba.id = b.id
left join authors a on a.id = ba.id
group by b.id;