将数据从整数字段复制到jsonb字段

时间:2018-02-08 08:08:24

标签: sql postgresql

我有以下架构

CREATE TABLE survey_results (
    id integer NOT NULL,
    raw jsonb DEFAULT '{}'::jsonb,
    survey_id integer NOT NULL,
    created_at timestamp without time zone,
    updated_at timestamp without time zone  
);

INSERT INTO survey_results (id, survey_id, raw, created_at, updated_at)
    VALUES (1, 10, '{"survey": {}}', '2018-01-10', '2018-01-11');

INSERT INTO survey_results (id, survey_id, raw, created_at, updated_at)
    VALUES (2, 20, '{"survey": {}}', '2018-01-12', '2018-01-12');

我想将survey_id值复制到raw->survey->survey_id键。我试图用以下方式做到这一点,但那不起作用:

UPDATE survey_results SET raw#>>'{survey, survey_id}' = survey_id;

在PostgreSQL中有没有办法呢?

http://sqlfiddle.com/#!17/ed50f/1

1 个答案:

答案 0 :(得分:1)

您需要使用jsonb_set()

update survey_results 
   set raw = jsonb_set(raw, '{survey, survey_id}', to_jsonb(survey_id), true);

在线示例:http://rextester.com/GTBTY13915

相关问题