MySQL更新列,它是另一列中的值

时间:2013-12-20 06:15:56

标签: mysql sql database

这是我之前与我的查询相关的问题。 MySQL select column which is a value in another column

问题是想要对提取的值进行操作并将其存储回原始数据库。我尝试过使用update& case但我无法实现它。

update msisdn_table
   CASE reason
     WHEN 'NoAnswer' THEN (case when (NoAnswer>0) then update msisdn_table set NoAnswer = NoAnswer-1 end)
     WHEN 'NetworkBusy' THEN (case when NetworkBusy>0 then update msisdn_table set NetworkBusy = NetworkBusy-1 end)
     WHEN 'CallRejection' THEN (case when CallRejection>0 then update msisdn_table set CallRejection = CallRejection-1 end)
     WHEN 'Unavailable' THEN (case when Unavailable>0 then update msisdn_table set Unavailable = Unavailable-1 end)
   END 

任何帮助?

2 个答案:

答案 0 :(得分:1)

如果你想做一个陈述

,请尝试这种方式
UPDATE msisdn_table
   SET NoAnswer      = IFNULL(IF(reason = 'NoAnswer',      
                                 NULLIF(NoAnswer,      0) - 1, NoAnswer), 0), 
       NetworkBusy   = IFNULL(IF(reason = 'NetworkBusy',   
                                 NULLIF(NetworkBusy,   0) - 1, NetworkBusy), 0), 
       CallRejection = IFNULL(IF(reason = 'CallRejection', 
                                 NULLIF(CallRejection, 0) - 1, CallRejection), 0), 
       Unavailable   = IFNULL(IF(reason = 'Unavailable',   
                                 NULLIF(Unavailable,   0) - 1, Unavailable), 0)
  WHERE reason IN('NoAnswer', 'NetworkBusy', 'CallRejection', 'Unavailable');

注意:

  1. 我用较简洁的CASE更改了IF(),但如果你更喜欢它,你可以用同样的方式使用它。
  2. 这种方法有一个可能的副作用,因为它总是使用new或old值更新列。例如,如果您在表上定义了触发器,则可能很重要。
  3. 您希望应用WHERE子句以确保包含其他reason代码的行不受影响
  4. 这是 SQLFiddle 演示

答案 1 :(得分:0)

update msisdn_table set  NoAnswer = NoAnswer-1 where (NoAnswer>0) ;
update msisdn_table set  NetworkBusy = NetworkBusy-1 where (NetworkBusy = NetworkBusy-1) ;
update msisdn_table set  CallRejection = CallRejection-1 where (CallRejection>0) ;
update msisdn_table set  'Unavailable' = 'Unavailable'-1 where (Unavailable>0) ;