PostgreSQL ON CONFLICT DO UPDATE with not null column and COALESCE EXCLUDED column

时间:2018-01-15 17:57:35

标签: postgresql constraints upsert

我想使用可能包含not null约束违规但不会引发错误的数据执行UPSERT。我希望跳过建议的行,而不是错误。

架构:

               Table "public.appointments"
    Column   |            Type             |  Modifiers
-------------+-----------------------------+--------------
 id          | bigint                      | not null
 location_id | bigint                      | not null
 time        | timestamp without time zone | not null
 status      | text                        | not null
Indexes:
    "appointments_pkey" PRIMARY KEY, btree (id)
    "for_upsert" UNIQUE CONSTRAINT, btree (id, location_id)

现有记录:

 id | location_id | status |       time         
----+-------------+--------+----------------------
  1 |           2 | sched  | 2017-12-15 01:10:00
  2 |           2 | sched  | 2017-12-19 01:30:00

查询:

INSERT INTO "objects" ("id", "location_id", "time")
  VALUES (1, 2, 'sched', '2017-10-31 19:25:00'),
         (2, 2, 'canc', NULL),
         (3, 2, 'canc', NULL)
  ON CONFLICT ON CONSTRAINT for_upsert DO UPDATE
    SET "time" = COALESCE(EXCLUDED."time", "objects"."time"),
        "status" = EXCLUDED."status"

当存在time非空的记录时,我希望status更新,而不管EXCLUDED."time"值(COALESCE尝试做什么)。但是,如果没有现有记录,并且新建议的行为空time,我不希望插入行或引发错误。

1 个答案:

答案 0 :(得分:0)

添加此子句:

    WHERE COALESCE(EXCLUDED."time", "appointments"."time") IS NOT NULL;
DO UPDATE SET...似乎有用之后