【发布时间】: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。你能发布原始查询