按不同表

时间:2018-03-05 11:21:30

标签: sql postgresql join sql-update

我的数据库中有以下架构:

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

CREATE TABLE slide_results (
    id integer NOT NULL,
    survey_result_id integer NOT NULL,
    slide_id integer NOT NULL,
    created_at timestamp without time zone,
    updated_at timestamp without time zone  
);



INSERT INTO survey_results (id, raw, created_at, updated_at)
    VALUES (1, '[{"id": "1", "finished_at": 1517421628092}, {"id": "2", "finished_at": 1517421894736}]', now(), now());


INSERT INTO slide_results (id, survey_result_id, slide_id, created_at, updated_at)
    VALUES (1, 1, 1, now(), now());

INSERT INTO slide_results (id, survey_result_id, slide_id, created_at, updated_at)
    VALUES (2, 1, 2, now(), now());    

问题出在slide_results表内。此表中的created_at列包含无效数据。我想将所有slide_results created_at更新为与raw->finished_at的值相同。

想知道在PostgreSQL中做这样的操作吗?

这是sqlfiddle的链接:

http://sqlfiddle.com/#!17/c47fc

1 个答案:

答案 0 :(得分:1)

我相信这可以做你想要的:

update slide_results
    set created_at = timestamp 'epoch' + (raw#>>'{1,"finished_at"}')::bigint * interval '1 millisecond'
    from survey_results sr
    where slide_results.survey_result_id = sr.id;