如何使用PostgreSQL Upsert使用INSERT ON CONFLICT语句在不同的位置条件下更新多列

时间:2019-02-01 23:53:48

标签: postgresql upsert

假设我有一个这样的表

create schema test;
CREATE TABLE test.customers (
customer_id serial PRIMARY KEY,
name VARCHAR UNIQUE,
email VARCHAR NOT NULL,
active bool NOT NULL DEFAULT TRUE,
is_active_datetime                   TIMESTAMP(3) NOT NULL DEFAULT'1900-01-01T00:00:00.000Z'::timestamp(3)
updated_datetime                     TIMESTAMP(3) NOT NULL DEFAULT '1900-01-01T00:00:00.000Z'::timestamp(3),
);

现在,如果我想在冲突email上更新name

WHERE $tableName.updated_datetime < excluded.updated_datetime

,我想在冲突is_active_datetime上更新name,但是此更新的条件是活动标志已更改。

WHERE customer.active != excluded.active

基本上想跟踪何时更改了活动状态。所以我可以在这样的单个语句中做到这一点

初始插入:

insert  INTO test.customers (NAME, email)
VALUES
('IBM', 'contact@ibm.com'),
(
'Microsoft',
'contact@microsoft.com'
 ),
(
 'Intel',
 'contact@intel.com'
);

为了达到我的目的,我正在尝试以下方法:

select * from test.customers;

INSERT INTO customers (name, email)
VALUES
(
'Microsoft',
'hotline@microsoft.com'
)
ON CONFLICT (name)
DO
UPDATE
SET customers.email = EXCLUDED.email
WHERE $tableName.updated_datetime < excluded.updated_datetime
on CONFLICT (name)
do
update
set is_active_datetime = current_timestamp()
WHERE customer.active != excluded.active ;

有可能这样做吗?如何使用此方法执行此操作。

1 个答案:

答案 0 :(得分:1)

您可以在单个CASE中用DO UPDATE clause个条件更新多个列。

INSERT INTO customers  (
    name
    ,email
    ,updated_datetime
    )
VALUES (
    'Microsoft'
    ,'hotline@microsoft.com'
    ,now()
    ) ON CONFLICT(name) DO

UPDATE
SET email = CASE 
        WHEN customers.updated_datetime < excluded.updated_datetime
            THEN excluded.email
        ELSE customers.email --default when condition not satisfied
        END
    ,is_active_datetime = CASE 
        WHEN customers.active != excluded.active
            THEN current_timestamp
        ELSE customers.is_active_datetime
    END;

Demo