表格中有一个jsonb字段。我想更新一个单独的键值,所以我使用的是jsonb_set方法。我想要更新的密钥是变量。
这是我要更新的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.
如何一次更新两个键?并且vote_count
也是一个整数,所以我需要它进行双重转换才能生成jsonb
vote_count::text::jsonb
还有其他办法吗?
答案 0 :(得分:0)
根据PostgreSQL documentation,python flask_basic.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Nov/2018 14:14:39] "GET / HTTP/1.1" 404 -
函数的签名为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;