【问题标题】:SQL update using a select case statement使用 select case 语句进行 SQL 更新
【发布时间】:2023-03-08 01:11:02
【问题描述】:

使用“选择案例”进行表更新时遇到问题。

作为一个普通的 select case 语句(不更新表),这个查询完美地工作:

select case
    when t1.id in (select t2.id from t2 where [condition1] then 'aaa'
    when t1.id in (select t3.id from t3 where [condition2] then 'bbb'
    when t1.id in (select t4.id from t4 where [condition3] then 'ccc'
    else 'ddd'
end
from owner.t1;

但是,当我尝试在更新语句中使用相同的“选择案例”语句时,我收到一条错误消息,指出子查询返回多于 1 行。这是不起作用的更新查询:

update owner.t1
set t1.var2 =
(select case
    when t1.id in (select t2.id from t2 where [condition1] then 'aaa'
    when t1.id in (select t3.id from t3 where [condition2] then 'bbb'
    when t1.id in (select t4.id from t4 where [condition3] then 'ccc'
    else 'ddd'
end
from owner.t1);

当我将代码更改为以下代码时,它的运行速度非常慢。可能对我的目的来说太慢了。

update owner.t1
set t1.var2 =
(select case
    when t2.id in (select t2.id from t2 where [condition1] then 'aaa'
    when t2.id in (select t3.id from t3 where [condition2] then 'bbb'
    when t2.id in (select t4.id from t4 where [condition3] then 'ccc'
    else 'ddd'
end
from owner.t2
where t2.id = t1.id);

所以我的问题是为什么我必须在辅助表中引用我的 id 而不是我要更新的表? 'where' 语句中的这种额外检查是否会为操作增加大量额外时间?

【问题讨论】:

  • 您的第一个更新查询不应抛出该错误,因为您使用的是IN。你能发布原始查询

标签: sql oracle select case


【解决方案1】:

为什么不这样做呢?

update owner.t1
    set t1.var2 = (case when t1.id in (select t2.id from t2 where [condition1] then 'aaa'
                        when t1.id in (select t3.id from t3 where [condition2] then 'bbb'
                        when t1.id in (select t4.id from t4 where [condition3] then 'ccc'
                        else 'ddd'
                   end);

【讨论】:

  • 感谢@Gordon 的建议。这行得通,而且比我所做的更有说服力。但是,我仍然有时间问题,但我发现这完全取决于否。更新。
猜你喜欢
  • 2012-12-05
  • 2012-05-18
  • 2014-12-05
  • 2019-03-17
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多