【问题标题】:Update existing records by data in different table通过不同表中的数据更新现有记录
【发布时间】:2018-03-05 11:21:30
【问题描述】:

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

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

【问题讨论】:

  • 这些表是如何关联的?
  • slide_results 表有survey_result_id 外键。

标签: sql postgresql join sql-update


【解决方案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;

【讨论】:

  • 此查询有效,但是当某些幻灯片结果在 json 中没有 finished_at 键时,它会失败并出现以下错误:ERROR: null value in column "created_at" violates not-null constraint Detail: Failing row contains (1, 1, 1, null, 2018-03-05 12:29:10.746283).
  • 这也不能正常工作。那些finished_at 是不同的,但在尝试您的查询后,所有幻灯片结果 created_at 都是相同的:sqlfiddle.com/#!17/4c996/1
  • @MateuszUrbański 。 . .您的 SQL Fiddle 只有一个值连接到两条记录。因此,结果总是一样的。
  • 我有两个幻灯片结果属于同一个survey_result。但是当你看 raw['slides'] 你会发现那些finished_at是不同的。幻灯片结果表中的第一条记录应已 created_at 更新为:1517421628092,第二条记录应更新为 1517421894736。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 2013-03-06
  • 2013-09-25
  • 1970-01-01
  • 2020-10-14
  • 2012-10-31
  • 1970-01-01
相关资源
最近更新 更多