一、问题描述
使用postgresql对json的特性使用sql批量处理json中某个属性的值
结构如下:
{"id": 1,"parentId": 123,"globalParameters": [{"value": "date","boardId": 123,"canReName": false}]
}
想要替换boardId的值
二、解决方案
有没有办法获取所选JSON数组元素的索引并将SELECT语句和UPDATE语句合并为一个?
update t_data
settent_info= jsonb_set(tent_info::jsonb,array['globalParameters', elem_index::text, 'boardId'],parentid::text::jsonb,true)
from (select pos- 1 as elem_index,elem from t_data , jsonb_array_elements(tent_info::jsonb->'globalParameters') with ordinality arr(elem, pos)wheretype_id =33
) sub
wheretype_id =33;
基本执行上面就可以批量处理josn数组里面boardId的属性值了
三、处理单个属性值
update t_data set
--content_info = jsonb_set(tent_info::jsonb,'{id}'::text[],id::text::jsonb)
content_info = jsonb_set(tent_info::jsonb,'{parentId}'::text[],parentid::text::jsonb)
where ype_id =33
因为是更新同一个tent_info字段,所有得分两次执行才行。