问题描述
我想通过消除对同一子查询的 3 次调用来优化以下过程。我以为我可以在存储过程中创建一个临时表并更新它,但不知道该怎么做。欢迎任何其他方式来做到这一点。
update some_table SET
status = (
case when 'OVERDUE' in (select status from other_table temp where Id = temp.Id)
then 'OVERDUE'
when 'UPCOMING' in (select status from other_table temp where Id = temp.Id)
then 'UPCOMING'
when 'PAID' in (select status from other_table temp where Id = temp.Id)
then 'PAID'
else
null
END
)
解决方法
我建议使用左连接执行更新:
UPDATE t1
SET t1.status = t2.status
FROM some_table t1
LEFT JOIN other_table t2 ON t2.Id = t1.Id
,
可能的解决方案是
update s
SET
status = Case temp.Status
when 'OVERDUE'
then 'OVERDUE'
when 'UPCOMING'
then 'UPCOMING'
when 'PAID'
then 'PAID'
else null
END
FROM some_table S LEFT JOIN
other_table temp ON
s.Id = temp.Id
,
如果 other_table temp where Id = temp.Id
中有多个记录,那么您可以使用以下查询:
update some_table SET status =
(select case when count(case when status = 'OVERDUE' then 1 end) > 0 then 'OVERDUE'
when count(case when status = 'UPCOMING' then 1 end) > 0 then 'UPCOMING'
when count(case when status = 'PAID' then 1 end) > 0 then 'PAID'
end
from other_table temp where Id = temp.Id)
,
我实际上建议这样的短语:
update some_table
set status = (select top (1) ot.status
from other_table ot join
(values ('OVERDUE',1),('UPCOMING',2),('PAID',3)
) v(status,ord)
on ot.status = v.status
where ot.id = some_table.id
order by v.ord
);
我不喜欢重复特定的 status
值。这使用了 values
语句,因此它们在代码中只包含一次。