更新具有不同条件的几列

时间:2019-04-25 17:13:04

标签: sql postgresql insert-update

我有INSERT语句,其中通过其他表中的SELECT提供值。关于冲突,我要更新几列。我只是想知道是否可以设置每个符合唯一条件的列

现在我有可行的解决方案,但这并不理想。

基本上像这样的东西会符合我想要的结果。

WITH table_a (
 --joining two tables
)

INSERT INTO table_b
SELECT * FROM table_a
ON CONFLICT
ON CONSTRAINT table_b_pkey DO UPDATE
SET column_a = EXCLUDED.column_a
WHERE table_b.column_a < EXCLUDED.column_a
OR 
SET column_b = EXCLUDED.column_b
WHERE table_b.column_b < EXCLUDED.column_b

1 个答案:

答案 0 :(得分:2)

使用CASE,例如:

INSERT INTO table_b
SELECT * FROM table_a
ON CONFLICT
ON CONSTRAINT table_b_pkey DO UPDATE
SET 
    column_a = CASE 
        WHEN table_b.column_a < EXCLUDED.column_a 
        THEN EXCLUDED.column_a 
        ELSE table_b.column_a END,
    column_b = CASE 
        WHEN table_b.column_b < EXCLUDED.column_b 
        THEN EXCLUDED.column_b 
        ELSE table_b.column_b END