简体   繁体   English

MySQL触发器中的添加未按预期工作

[英]Addition in MySQL trigger not working as expected

I'm doing some addition as part of a mysql trigger. 我正在做一些附加操作,作为mysql触发器的一部分。 The added value is added a to a column on the table. 将增加的值添加到表上的列。 The code is as follows; 代码如下:

BEGIN

  IF NEW.Status = 'processed' AND NEW.Success = 1 THEN
     INSERT INTO crm_master 
       (msisdn, last_action_date, source, contract_type, revenue,inc)       
     VALUES 
       (new.msisdn,NOW(), 'INC5', new.Contract_Type, revenue = revenue+5, 1)
     ON DUPLICATE KEY UPDATE last_action_date = NOW(),
                             contract_type = new.Contract_Type,
                             revenue = revenue+5,
                             inc = 1;
  END IF;
END

The column revenue in the table crm_master is set to default of 0 表crm_master中的列收入设置为默认值0

The problem is that I'm getting unexpected results with incorrect values and in some cases 0 even though there should never be a 0 value. 问题是我得到了不正确的值,在某些情况下为0的意外结果,即使永远不应该有0值。

I don't think it's valid reference to default value revenue = revenue+5 in your insert statement. 我认为插入语句中对默认值revenue = revenue+5引用无效。 It should look like 它看起来像

 INSERT INTO crm_master 
   (msisdn, last_action_date, source, contract_type, revenue,inc)       
 VALUES 
   (new.msisdn,NOW(), 'INC5', new.Contract_Type, DEFAULT(revenue) +5, 1)
 ON DUPLICATE KEY UPDATE .... 

Or you can simply do 或者你可以简单地做

INSERT INTO ....
VALUES 
   (new.msisdn,NOW(), 'INC5', new.Contract_Type, 5, 1) ...

*Your update part of INSERT ... ON DUPLICATE KEY UPDATE is ok. *您的INSERT ... ON DUPLICATE KEY UPDATE更新部分是可以的。

INSERT INTO sometable( column ) VALUES ( column = column + 5 );

is equivalent to 相当于

INSERT INTO sometable( column ) VALUES ( 0 );

because (column = column+5) evaluates to 0 as column is never equal to column+5. 因为(column = column + 5)求值为0,因为column永远不等于column + 5。 This syntax is ok for UPDATE query, but for INSERT you should provide an explicit value, like 对于UPDATE查询,这种语法是可以的,但是对于INSERT,您应该提供一个明确的值,例如

INSERT INTO sometable( id, column ) VALUES ( 1, 5 )
ON DUPLICATE KEY UPDATE column = column + 5;

which would insert value 5 if there is no row with given id and add 5 to column if there is one. 如果不存在具有给定id的行,则将插入值5;如果没有,则将5插入列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM