具有多个唯一约束的Postgresql UPSERT

时间:2018-10-11 03:13:56

标签: postgresql upsert

我已经创建了一张表作为位置(世界上的城市)。

CREATE TABLE location (
    location_id BIGSERIAL PRIMARY KEY,
    location_name VARCHAR(100) NOT NULL,
    state_id INT,
    country_id INT NOT NULL,
    UNIQUE (location_name, state_id, country_id),
    FOREIGN KEY (state_id) REFERENCES state (state_id)
    ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (country_id) REFERENCES country (country_id)
    ON UPDATE CASCADE ON DELETE CASCADE
    );

CREATE UNIQUE INDEX loc_1_uni_idx ON location (location_name, country_id)
    WHERE state_id IS NULL;

此表具有两个唯一性检查:如果state_id为null,则location_name + country_id;如果state_id有值,则location_name + state_id + country_id。

当前,我想对该表进行upsert。对于上述两种情况,我都可以执行冲突处理:

INSERT INTO location(location_name, state_id, country_id) VALUES %s 
ON CONFLICT (location_name, state_id, country_id) 
DO UPDATE 
   SET country_id = EXCLUDED.country_id 
RETURNING location_id;

INSERT INTO location(location_name, state_id, country_id) VALUES %s 
ON CONFLICT (location_name, country_id) 
   WHERE state_id IS NULL 
DO UPDATE SET country_id = EXCLUDED.country_id 
RETURNING location_id;

但是,由于state_id可能存在或可能不存在,我该如何执行一次upsert来满足这两种情况?谢谢。

0 个答案:

没有答案