mysql中使用case语句更新表
我想使用case语句更新多个列,我实现了这一点,但这并不是我必须三次完成同一任务的最佳方式,我如何在一个语句中实现这是我的测试sql脚本:mysql中使用case语句更新表,mysql,sql,mysql-workbench,Mysql,Sql,Mysql Workbench,我想使用case语句更新多个列,我实现了这一点,但这并不是我必须三次完成同一任务的最佳方式,我如何在一个语句中实现这是我的测试sql脚本: Delimiter // create procedure test_f() begin update test set #### total#### test.total = case when test.currencyid='INR' then test.total/85.09 Else test.tota
Delimiter //
create procedure test_f()
begin
update test set
#### total####
test.total = case when test.currencyid='INR' then test.total/85.09
Else test.total End,
test.total = case when test.currencyid='SEK' then test.total/8.97
Else test.total End,
### Commission ####
test.commission = case when test.currencyid='INR' then test.commission/85.09
Else test.commission End,
test.commission = case when test.currencyid='SEK' then test.commission/8.97
Else test.commission End,
test.currencyid = case when test.currencyid in ('SEK','INR') then 'EUR'
Else test.currencyid End
WHERE test.currencyid in ('SEK','INR') ;
END //
现在我想根据currencyid更新所有三列 对于第一种情况,您可以尝试以下方法: 而不是:
update test set
#### total####
test.total = case when test.currencyid='INR' then test.total/85.09
Else test.total End,
test.total = case when test.currencyid='SEK' then test.total/8.97
Else test.total End,
改为:
update test set
#### total####
test.total =
case when test.currencyid='INR' then test.total/85.09
when test.currencyid='SEK' then test.total/8.97
Else test.total
End,
对
##########
我倾向于将查询写为:
update test t
set t.total = t.total / (case when t.currencyid = 'INR' then 85.09 else 8.97 end),
t.commission = t.commission / (case when t.currencyid = 'INR' then 85.09 else 8.97 end),
t.currency = 'EUR'
where t.currencyid in ('INR', 'SEK') ;
where
子句将货币限制为上述两种情况,因此案例
只需测试这两种情况。简化case语句还可以更清楚地表明,两种计算都使用相同的逻辑。我想更新总计、佣金和货币,例如更新表testset commission=123,total=123,currencyid='EUR',其中currencyid='euro'