我正在测试一些条件渲染,看看它在小规模上的表现是否符合预期,然后再在更大的表上实现。
目标是创建一个更新查询,该查询仅更新用户输入新数据的列,如果没有数据,则不对这些列执行任何操作
这是我测试时的情况。具有空值的行未更新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;
Run Code Online (Sandbox Code Playgroud)
这是我想要生成的一个简单示例($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
Run Code Online (Sandbox Code Playgroud)
我期望发生的是插入创建一个 id 为 1 的行和一个等于 null 的 val 单元格。
然后在更新查询中,我认为更新将检查第 1 行 val 中存储的数据是否不等于输入值,如果为真,则输入值将设置为第 1 行的 val。
这个逻辑和语法正确吗?如果不是,什么是不正确的?
wil*_*ser 10
假设用户输入$1永远不会为 NULL:
update tester
set val = $1
where id = 1
and val <> $1 -- avoid updating with the same value
;
Run Code Online (Sandbox Code Playgroud)
注意:您的:
`case when val != $1 then $1 else val end`
Run Code Online (Sandbox Code Playgroud)
可以简化为:
`case when val <> $1 then $1 else $1 end`
Run Code Online (Sandbox Code Playgroud)
或者:
`$1`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24419 次 |
| 最近记录: |