sql - 在 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;
输出:
错误:“现在”或附近的语法错误
我怎样才能做到这一点?这会带来更好的性能吗?
解决方案
如手册中所述,表单中的“简单”案例表达式(不是“语句”)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
条件,你就不能使用它。
两个版本的性能应该相同。至少与更新表中的行并将这些更改写入磁盘所需的工作相比,它可以忽略不计。
推荐阅读
- c# - 重新加载关卡按钮 - 重新开始到以前的分数 - Unity 2D
- environment - 什么是编程环境?
- javascript - 无法访问函数内部的地理位置
- php - 如何使用php将用户数据保存在不同的页面中
- flutter - 按下 Ctrl+Shift+I 短以将代码格式化为可读形式后,vscode 出现飞镖和颤振的无效语法错误
- swift - swiftUI如何在键盘上有搜索按钮
- javascript - 如何根据数据点索引更改元素绘制顺序?
- applescript - Applescript 和“笔记”:在新窗口中打开笔记
- cakephp - Security.salt 问题
- java - JDA如何通过ID获取消息