0
使用'select case'进行表更新时出现问题。使用select case语句进行SQL更新
作为一个正常的选择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;
然而,当我尝试使用相同的“选择情况”语句在更新语句,我得到一个错误,说明一个子查询返回多于一行。这是不起作用的更新查询:
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'而抛出该错误。你可以发布原始查询 –