我有以下架构:
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"}
我该如何解决?
答案 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);
答案 2 :(得分:1)
您可以创建第二个JSON字典并将其与scores
:
UPDATE survey_results SET scores = scores || FORMAT('{"risk-score":%s}', scores->>'total')::JSONB;