我有INSERT语句,其中的值是通过SELECT from other表提供的冲突时,我正在更新几个列。我只是想知道是否可以设置每个列匹配唯一条件
现在我有了解决方案,但效果并不理想。
基本上这样的结果会符合我的期望。。

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

最佳答案

使用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

10-08 04:33