首页 > 解决方案 > 在 CASE 表达式中使用 between 谓词

问题描述

我想target_column根据时间进行更新column1。我可以这样做:

update table set target_column = case 
when (column1 between now() and now() - interval '1 year') then 1.0
when (column1 between now() - interval '1 year' and now() - interval '2 years') then 2.0 
else 3.0 end;

但我不能这样做:

update table set target_column = case column1 
when (between now() and now() - interval '1 year') then 1.0
when (between now() - interval '1 year' and now() - interval '2 years') then 2.0 
else 3.0 end;

输出:

错误:“现在”或附近的语法错误

我怎样才能做到这一点?这会带来更好的性能吗?

标签: sqlpostgresqlcase

解决方案


如手册中所述,表单中的“简单”案例表达式(不是“语句”)case some_thing when ... 允许使用运算符将​​列(实际上是表达式)与常量值进行比较的相等条件=

所以以下内容:

case some_column 
   when 1 then 'one'
   when 2 then 'two'
   else 'Something else'
end 

相当于:

case 
   when some_column = 1 then 'one'
   when some_column = 2 then 'two'
   else 'Something else'
end 

“简单”表达式 ( case some_column when ...) 不支持其他任何内容。

如果你想使用一个between条件,你就不能使用它。


两个版本的性能应该相同。至少与更新表中的行并将这些更改写入磁盘所需的工作相比,它可以忽略不计。


推荐阅读