我在表中有一个 jsonb 字段。我想更新一个单独的键值,所以我使用 jsonb_set 方法。我要更新的 key 在一个变量中。
这是我要更新的jsonb对象
{"yes":5,"total_votes":6,"no":1}
关键变量vote_to
是yes
。
这是我的尝试
update polls set result = jsonb_set(result, ('{'||vote_to||'}'),vote_count::text::jsonb) where id=_poll_id;
错误是
ERROR: function jsonb_set(jsonb, text, jsonb) does not exist
LINE 1: update polls set result = jsonb_set(result, ('{'||vote_to||'...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
如何一次更新两个 key ?而且 vote_count
是一个整数,所以我需要它进行双重转换以制作 jsonb
vote_count::text::jsonb
还有其他方法吗?
最佳答案
根据PostgreSQL documentation jsonb_set
函数的签名是 jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean])
。所以你必须将第二个参数转换为 text[]
。
使用这个:
CREATE TABLE polls (id INTEGER, result jsonb, vote_count jsonb);
INSERT INTO polls VALUES (1, '{"yes":5,"total_votes":6,"no":1}'::jsonb, '{"v": 1}'::jsonb);
CREATE OR REPLACE FUNCTION test(poll_id INTEGER, vote_to TEXT) RETURNS VOID AS
$$
DECLARE
to_update jsonb;
BEGIN
update polls set result = jsonb_set(result, ('{'||vote_to||'}')::text[], vote_count) where id=poll_id;
END;
$$ LANGUAGE plpgsql;
SELECT test(1, 'yes');
SELECT * FROM polls;
将得到以下结果:
id | result | vote_count
----+----------------------------------------------+------------
1 | {"no": 1, "yes": {"v": 1}, "total_votes": 6} | {"v": 1}
(1 row)
关于sql - 如果路径键在变量 postgresql 中,如何更新 jsonb 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074696/