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'而拋出該錯誤。你可以發佈原始查詢 –