PostgreSQL - 从jsonb字段复制值格式错误

时间:2018-02-16 12:04:59

标签: sql postgresql

我有以下架构:

CREATE TABLE survey_results (
    id integer NOT NULL,
    scores jsonb DEFAULT '{}'::jsonb
);

INSERT INTO survey_results (id, scores)
    VALUES (1, '{"total": 10}');

INSERT INTO survey_results (id, scores)
    VALUES (2, '{"total": 10}');

我想将total键的值复制到risk-score键,这由以下查询完成:

update survey_results set scores = jsonb_set(scores, '{risk-score}', to_jsonb(scores#>>'{total}'), true);

问题是复制的值是字符串而不是整数:

{"total": 10, "risk-score": "10"}

我该如何解决?

http://sqlfiddle.com/#!17/ea916/13

3 个答案:

答案 0 :(得分:2)

只需将运营商更改为#>

即可
update survey_results 
set scores = jsonb_set(scores, '{risk-score}', to_jsonb(scores#>'{total}'), true);

答案 1 :(得分:1)

使用->运算符:

update survey_results 
set scores = jsonb_set(scores, '{risk-score}', scores->'total', true);

SqlFiddle

答案 2 :(得分:1)

您可以创建第二个JSON字典并将其与scores

连接起来
UPDATE survey_results SET scores = scores || FORMAT('{"risk-score":%s}', scores->>'total')::JSONB;