我有一张桌子,例如:
ID | Details
1 | {"name": "my_name", "phone": "1234", "address": "my address"}
2 | {"name": "his_name", "phone": "4321", "address": "his address"}
在此,Details是一个jsonb对象。我想在jsonb中添加另一个名为“标签”的字段,该字段应具有一些特定的键。在这种情况下,为“名称”,“电话”。执行查询后的最终状态应为:
ID | Details
1 | {"tags": {"name": "my_name", "phone": "1234"},"name": "my_name", "phone": "1234", "address":"my address"}
2 | {"tags": {"name": "his_name", "phone": "4321"},"name": "his_name", "phone": "4321", "address":"his address"}
我可以考虑完成以下步骤:
我想不出相应的postgres查询应该如何。请指导。
答案 0 :(得分:1)
当然要使用连接运算符!
https://www.postgresql.org/docs/current/functions-json.html
update t1 set details = details || '{"tags": {"name": "my_name"}}' where id = 1
答案 1 :(得分:1)
使用jsonb_build_object
update t set details
= jsonb_build_object ( 'tags',
jsonb_build_object( 'name', details->>'name', 'phone',details->>'phone')
)
|| details
答案 2 :(得分:0)
您可以提取您感兴趣的键,构建一个新的json值并将其附加到该列:
update the_table
set details = details || jsonb_build_object('tags',
jsonb_build_object('name', details -> 'name',
'phone', details -> 'phone'));