在mysql中使用case语句更新表

时间:2014-02-27 11:12:38

标签: 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.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更新所有三列。

2 个答案:

答案 0 :(得分:0)

您可以尝试第一种情况: 而不是:

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,

### Commission ####

执行相同的操作

答案 1 :(得分:0)

我倾向于将查询写成:

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只需测试这两种情况。简化case语句还可以清楚地表明,两种计算都使用相同的逻辑。