sql - 如果路径键在变量 postgresql 中,如何更新 jsonb 值

标签 sql json postgresql jsonb

我在表中有一个 jsonb 字段。我想更新一个单独的键值,所以我使用 jsonb_set 方法。我要更新的 key 在一个变量中。

这是我要更新的jsonb对象

{"yes":5,"total_votes":6,"no":1}

关键变量vote_toyes

这是我的尝试

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/

相关文章:

sql - PostgreSQL 查询无匹配条件

c++ - 在哪里存储 C++ 应用程序的 SQL 代码?

sql - 需要帮助来修复查询 SQL Server

sql - 在oracle 12c上用ROWNUM锁定的更新跳过

java - 在 dynamodb 中存储 JSON 的可能方法

json - Three.js:减少模型文件大小的方法?

mysql - 翻译 MySQL 查询 - 我的解释正确吗?

javascript - 将不存在的日期数据添加到 JSON

sql - Postgres 截断 CASE 语句列

postgresql - Postgres : TRUNCATE and COPY in one transaction