PostgreSQL中的条件更新

8

我正在测试一些条件渲染,以便在较小的范围内检查其是否按预期工作,然后再将其应用于更大的表格。

目标是创建一个更新查询,仅在用户输入了新数据的列上进行更新,如果没有数据,则不对这些列执行任何操作。

这是我的 case when then 测试。具有 null 值的行未更新 newValue

drop table if exists tester

create table tester (
id serial primary key
val TEXT,
)

insert into tester (val) values (null)

select * from tester

update tester 
set val = case 
when val = null 
then 'newValue' 
else val 
end;

这是一个我想要生成的简单示例($1 是用户输入):

drop table if exists tester

create table tester (
id serial primary key
val TEXT,
)

insert into tester (val) values (null)

select * from tester

update tester 
set val = case 
when val != $1
then $1 
else val end
where id = 1

我期望的结果是插入一行,该行的id为1,val单元格的值为null。在更新查询中,如果行1上存储的val数据与输入值不相等,则更新将检查这一点。如果成立,则会将输入值设置为行1的val值。这个逻辑和语法正确吗?如果不正确,请指出错误所在。

1
如果你想将一列与 null 进行比较,请使用 CASE WHEN val IS NULL。使用等号是行不通的。 - Tim Biegeleisen
知道就好。你能做 CASE WHEN $1 IS NULL 吗? - Austin Callaghan
我不知道$1是什么,但是很可能会起作用。你正在使用带有Postgres的编程语言吗? - Tim Biegeleisen
3
简化版翻译:Coalesce 简短陈述 - dwir182
@TimBiegeleisen 是的,我在前端使用ReactJS,然后在服务器上使用NodeJS + ExpressJS。我正在使用postgresql。 - Austin Callaghan
1个回答

10
假设用户输入的 $1 永远不会为空:
update tester 
set val = $1
where id = 1
and val <> $1 -- avoid updating with the same value
    ;

注意:你的:
 `case when val != $1 then $1 else val end`

可以简化为:
 `case when val <> $1 then $1 else $1 end`

或者:

 `$1`

你能解释一下最后一个吗? - Austin Callaghan
如果 val <> $1 为假,则 val 和 $1 必须相等。(这是第一个) - wildplasser
我尝试了这个语句并且成功了:update tester set val = case when val <> NULL then 'peaches' else 'peaches' end where id = 1; 但后来我想应该检查一下输入是否为空,于是这样写:update tester set val = case when $1 <> NULL then $1 else val end where id = 1; 最后一个问题是,如果我要链式使用 case when 语句,在最后一个语句后面加上 where 条件语句,可以确定更新哪一行吗? - Austin Callaghan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接