在检查是否需要保留旧值或插入新值时向上插入postgres sql查询?

oyt4ldly  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(366)

我有一个postgressql查询,我想在那里执行upsert。我的 pk1, pk2 列是复合主键。我想更新3列 dk1, dk2, timek 如果与主键约束冲突。当我更新冲突列时,比如 timek 列,然后我需要检查新值是否小于旧值,并相应地选择是否需要使用旧值或新值。这是我的查询,但它抛出错误。我是postgresql的新手,有什么问题吗?

INSERT INTO data_reports (pk1, pk2, dk1, dk2, dk3, timek, valuek)  VALUES (?, ?, ?, ?, ?, ?, ?)  
ON CONFLICT (pk1, pk2) DO UPDATE SET 
dk1 = EXCLUDED.dk1, 
dk2 = CASE WHEN (dk2 < EXCLUDED.dk2) THEN EXCLUDED.dk2 ELSE dk2 END), // I believe dk2 (existing value in DB) is not selected but how to do that
timek = CASE WHEN (timek < EXCLUDED.timek) THEN EXCLUDED.timek ELSE timek END);
e3bfsja2

e3bfsja21#

您可以通过指定表名来引用更新前的列值:例如。 data_reports.dk2 .
开括号和闭括号,共有5个 ( s和7 ) s。
开始评论 -- ,或用 /* 以及 */ .

INSERT INTO data_reports (pk1,pk2,dk1,dk2,dk3,timek,valuek)
VALUES (1,1,9,9,9,9,9)
ON CONFLICT (pk1,pk2) DO
UPDATE
SET
    dk1 = EXCLUDED.dk1,
    dk2 =
    (CASE
        WHEN (data_reports.dk2 < EXCLUDED.dk2) THEN EXCLUDED.dk2
        ELSE data_reports.dk2
    END),
    timek =
    (CASE
        WHEN (data_reports.timek < EXCLUDED.timek) THEN EXCLUDED.timek
        ELSE data_reports.timek
    END);
li9yvcax

li9yvcax2#

仅供参考:您可以通过用最少的函数替换case表达式来简化:

insert into data_reports (pk1,pk2,dk1,dk2,dk3,timek,valuek)
values (1,1,9,9,9,9,9)
on conflict (pk1,pk2) do
update
set
    dk1 = excluded.dk1,
    dk2 = least(data_reports.dk2, excluded.dk2),
    timek = least(data_reports.timek, excluded.timek);

相关问题