我的PostgreSQL数据库中有一个像这样的JSON模式的JSON字段
{
"home":{
"lat":"37.774192",
"long":"-92.118511",
"address":"home address"
},
"work":{
"lat":"37.774192",
"long":"-92.118511",
"address":"work address"
},
"more":[
{
"id":"bRuKnd",
"name":"gym",
"lat":"37.774192",
"long":"-92.118511",
"address":"gym address"
},
{
"id":"eVdOlD",
"name":"fastfood",
"lat":"37.774192",
"long":"-92.118511",
"address":"fastfood addres"
},
{
"id":"SwkfcL",
"name":"Res",
"lat":"37.774192",
"long":"-92.118511",
"address":"Res address"
}
]
}
通过此查询,我可以获取“更多”或“工作”和“家庭”对象中的每个JSON字段
UPDATE items FROM (SELECT loc FROM public.tbl_user where uuid = '2fa7a484-f454-4d44-94be-a4011aee47b4') as o
,json_array_elements(o.loc#>'{more}') AS items where items->>'id' = 'eVdOlD' ;
我不知道如何在数据库中编辑或删除这些字段
我需要这些查询
答案 0 :(得分:0)
当您在postgres JSON中编辑值时,您所做的编辑不如用新内容替换行。
jsonb_set可能正是您想要的。
请参见https://www.postgresql.org/docs/current/functions-json.html
基于示例的简单形式:
sophia=> create table foo (bar jsonb);
CREATE TABLE
sophia=> insert into foo values ('{
"home":{
"lat":"37.774192",
"long":"-92.118511",
"address":"home address"
}}'::jsonb);
INSERT 0 1
sophia=> select * from foo;
bar
---------------------------------------------------------------------------------
{"home": {"lat": "37.774192", "long": "-92.118511", "address": "home address"}}
(1 row)
sophia=> update foo set bar = jsonb_set(bar, '{home,address}', '"29 Acacia Road"');
UPDATE 1
sophia=> select * from foo;
bar
-----------------------------------------------------------------------------------
{"home": {"lat": "37.774192", "long": "-92.118511", "address": "29 Acacia Road"}}
(1 row)
sophia=>
同样要删除:
sophia=> update foo set bar = jsonb_set(bar, '{home}', (bar -> 'home') - 'address');
UPDATE 1
sophia=> select * from foo;
bar
------------------------------------------------------
{"home": {"lat": "37.774192", "long": "-92.118511"}}
(1 row)
sophia=>