[英]Update a value in json column array of objects in postgresql raw query
I have a json type column in postgreSQL and I want to update the specific field in that json column.我在 postgreSQL 中有一个 json 类型的列,我想更新该 json 列中的特定字段。 Below is the column I want to update in,
[{"id":"xyyc","answered":false,"payable":true,"productIncentiveCost":{"incentive":0,"cost":0,"dollarIncentive":0,"dollarCost":0},"reward":0,"amountInDollar":0,"delayToNextProduct":"","extraDelayToNextProduct":""}]
.下面是我要更新的列,
[{"id":"xyyc","answered":false,"payable":true,"productIncentiveCost":{"incentive":0,"cost":0,"dollarIncentive":0,"dollarCost":0},"reward":0,"amountInDollar":0,"delayToNextProduct":"","extraDelayToNextProduct":""}]
。
I want to update the "reward" at 0 index of this column using postgreSQL raw query.我想使用 postgreSQL 原始查询更新此列的 0 索引处的“奖励”。
I have tried updating it using update method set and set_json but no luck.我尝试使用更新方法 set 和 set_json 更新它,但没有成功。
update data
set value = tmp.upd_json_arr
from (
select
jsonb_agg(jsonb_row || '{"reward": 167}') as upd_json_arr
from data,
jsonb_array_elements(value) jsonb_row
) tmp;
Details:细节:
jsonb_array_elements()
function. As a result you'll get jsonb rows.jsonb_array_elements()
function“扩展”您的 jsonb 数组。结果您将获得 jsonb 行。jsonb_row || '{"reward": 167}'
jsonb_row || '{"reward": 167}'
jsonb_row || '{"reward": 167}'
. jsonb_row || '{"reward": 167}'
。jsonb_agg()
function can help you to flatten all the jsonb rows into an array upd_json_arr
.jsonb_agg()
function 可以帮助您将所有 jsonb 行展平到数组upd_json_arr
中。upd_json_arr
is used in a set
-statement. upd_json_arr
在set
语句中使用。 This answer shows different ways to manipulate with jsonb fields.此答案显示了使用 jsonb 字段进行操作的不同方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.