PostgreSQL - 将数字值从jsonb字段复制到整数列

时间:2018-02-19 11:37:30

标签: sql postgresql

我有以下架构:

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

INSERT INTO survey_results (id, raw)
    VALUES (1, '{"survey": {"publish_id": 5}}');

我想通过以下更新将值从jsonb字段复制到整数列:

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

但这会让我回头:

ERROR: column "publish_id" is of type integer but expression is of type text Hint: You will need to rewrite or cast the expression. Position: 40

我该如何解决?

http://sqlfiddle.com/#!17/c50f2/4

1 个答案:

答案 0 :(得分:2)

just cast

UPDATE survey_results SET publish_id = (raw#>>'{survey, publish_id}')::int;         

https://www.postgresql.org/docs/current/static/functions-json.html

  

以指定路径获取JSON对象作为文本

因此您需要将文本转换为整数以匹配列数据类型