更新具有不同条件的多个列
updating for several columns with distinct conditions
我有 INSERT 语句,其中的值是通过来自其他 table 的 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
使用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
我有 INSERT 语句,其中的值是通过来自其他 table 的 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
使用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