【发布时间】:2021-08-04 05:18:10
【问题描述】:
这是我的 JSON 字段,其中有多个同名用户。我想将所有名为 Devang 的用户更新为 Dev
JSON
{
"user": [
{
"user_name": "Devang",
"user_weight": 0.7676846955248864
},
{
"user_name": "Meet",
"user_weight": 0.07447325861051013
},
{
"user_name": "Devang",
"user_weight": 0.056163873153859706
}
],
"address": [
{
"address_name": "India"
}
]
}
更新后的 JSON 将是
{
"user": [
{
"user_name": "Dev",
"user_weight": 0.7676846955248864
},
{
"user_name": "Meet",
"user_weight": 0.07447325861051013
},
{
"user_name": "Dev",
"user_weight": 0.056163873153859706
}
],
"address": [
{
"address_name": "India"
}
]
}
这里我尝试过这个查询,但由于子查询,只更新了第一次出现。
with cte as (
select id, ('{user,'||index-1||',user_name}')::text[] as json_path
from user_table, jsonb_array_elements(json_field->'user')
with ordinality arr(vals,index) where arr.vals->>'user_name' ='Devang'
)
update user_table
set json_field = jsonb_set(json_field,cte.json_path,'"Dev"',false)
from cte where user_table.id=cte.id;
也请看这个DEMO
任何答案将不胜感激
【问题讨论】:
-
使用适当的规范化数据模型会容易得多。
标签: sql json postgresql jsonb