我需要更新一个名为“verticals”的jsonb列,它所拥有的值数组就像HOM,BFB等。数组中没有键。
表:Product(verticals jsonb, code int)
存储在“verticals”列中的样本值是
[HOM,rst,NLF,WELSAK,HTL,TRV,EVCU,GRT]
我需要在“verticals”列中将值“HOM”更新为“XXX”,其中code = 1
我的预期产量是
[XXX,rst,NLF,WELSAK,HTL,TRV,EVCU,GRT]
因为您选择以非规范化方式存储数据,所以更新它比必须更复杂。
您需要首先取消数组(基本上规范化数据),替换值,然后将它们聚合并更新列:
update product p
set verticals = t.verticals
from (
select jsonb_agg(case when x.v = 'HOM' then 'XXX' else x.v end order by idx) as verticals
from product p2, jsonb_array_elements_text(p2.verticals) with ordinality as x(v,idx)
where code = 1
) t
where p.code = t.code;
这假设product.code
是主要(或唯一)密钥!
在线示例:http://rextester.com/KZQ65481
如果数组元素的顺序不重要,这会变得更容易:
update product
set verticals = (verticals - 'HOM')||'["XXX"]'
where code = 1;
这将从数组中删除元素“HOM”(无论位置如何),然后将“X”附加到数组的末尾。
你应该使用jsonb_set(target jsonb,path text [],new_value jsonb [,create_missing boolean])和array_position()OR array_replace(anyarray,anyelement,anyelement)
https://www.postgresql.org/docs/9.5/static/functions-json.html https://www.postgresql.org/docs/10/static/functions-array.html