[英]Update certain array elements of a json array in PostgreSQL 9.4
I have a table like this;我有一张这样的桌子;
CREATE TABLE test (
id BIGSERIAL PRIMARY KEY,
data JSONB
);
INSERT INTO test(data) VALUES('[1,2,"a",4,"8",6]'); -- id = 1
INSERT INTO test(data) VALUES('[1,2,"b",4,"7",6]'); -- id = 2
How to update element data->1
and data->3
into something else without PL/*
?如何在没有PL/*
情况下将元素data->1
和data->3
为其他内容?
You cannot manipulate selected elements of a json
/ jsonb
type directly.您不能直接操作json
/ jsonb
类型的选定元素。 Functionality for that is still missing in Postgres 9.4 (see @Craig's comment). Postgres 9.4 中仍然缺少该功能(请参阅@Craig 的评论)。 You have to do 3 steps:你必须做3个步骤:
To replace the 3rd element of the json array ( data->3
) in the row with id = 1
with a given (new) value ( '<new_value>'
) in pg 9.4 :用 pg 9.4 中的给定(新)值( '<new_value>'
)替换id = 1
行中json 数组( data->3
)的第三个元素:
UPDATE test t
SET data = t2.data
FROM (
SELECT id, array_to_json(
array_agg(CASE WHEN rn = 1 THEN '<new_value>' ELSE elem END))
) AS data
FROM test t2
, json_array_elements_text(t2.data) WITH ORDINALITY x(elem, rn)
WHERE id = 1
GROUP BY 1
) t2
WHERE t.id = t2.id
AND t.data <> t2.data; -- avoid empty updates
About json_array_elements_text()
:关于json_array_elements_text()
:
About WITH ORDINALITY
:关于WITH ORDINALITY
:
You can do this from PostgreSQL 9.5 with jsonb_set :您可以使用jsonb_set从 PostgreSQL 9.5 执行此操作:
INSERT INTO test(data) VALUES('[1,2,"a",4,"8",6]');
UPDATE test SET data = jsonb_set(data, '{2}','"b"', false) WHERE id = 1
Try it out with a simple select:用一个简单的选择试试看:
SELECT jsonb_set('[1,2,"a",4,"8",6]', '{2}','"b"', false)
-- [1, 2, "b", 4, "8", 6]
And if you want to update two fields you can do:如果你想更新两个字段,你可以这样做:
SELECT jsonb_set(jsonb_set('[1,2,"a",4,"8",6]', '{0}','100', false), '{2}','"b"', false)
-- [100, 2, "b", 4, "8", 6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.