【发布时间】:2020-02-22 08:36:56
【问题描述】:
Json 请求:
INSERT INTO test.demotbl (data)
VALUES ('{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER"
},
{
"id": "RO",
"z2": false,
"z3": "SELECT"
}
]
}
}'::jsonb)
我想根据 id "id": "RO" 更新归档的 z4。
当我需要更新查询下方使用的 z4 字段时,我在这里遇到了类似的用例:
with zd as (select ('{x4,y1,'||index-1||',z4}')::text[] as path
from table1
,jsonb_array_elements((field1->>'x4')::jsonb->'y1')
with ordinality arr(x,index)
where x->>'id'='RO'
)
update table1
set field1=jsonb_set(field1,zd.path,to_jsonb('[ { "name": "john" } ]'::jsonb),false)
from zd
但是现在在当前的 json 文件中没有提交的 X4,我需要添加“z4”:[{ “姓名”:“约翰” } 而不是仅仅更新字段
预期输出:
{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER"
},
{
"id": "RO",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "john"
}]
}
]
}
}
是否可以修改上述查询或建议一个新查询同时适用于添加(如果归档 z4 不存在)和更新归档 z4 示例 "z4": [{ "name": "john" },{ "name ": "Steve" }] 如果归档 z4 存在。
【问题讨论】:
-
"z4": [{ "name": "john", "name":"steve" }] 在预期输出中看起来不同。你想让 z4 成为一个数组吗?
-
@Bjarni Ragnarsson 是的,抱歉打错了,应该是 "z4": [{ "name": "john" },{ "name": "Steve" }]
标签: postgresql jsonb