使用“选择案例”进行表格更新时遇到问题。
作为正常的选择案例语句(不更新表),此查询可以完美运行:
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;
但是,当我尝试在更新语句中使用相同的“select case”语句时,我收到一条错误,指出子查询返回的行数超过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'语句中额外检查,为操作增加了很多额外的时间吗?
答案 0 :(得分:0)
为什么不这样做?
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);