创建触发器以添加列数据但不减去

时间:2018-11-22 13:51:19

标签: mysql

经过几次Google搜索,我来了。

我有一个MYSQL数据库表名称users。 我有两列account_balanceearned_total

在PHP端,当用户执行某些操作时,我会在多个位置更新account_balance。我想记录一下他到目前为止已经赚了多少钱。因此,我创建了一个earned_total列。 使用触发器(或任何其他方法)而不修改我的PHP代码,如何在earned_total列更新时也更新account_balance列?

记住用户退出时,earned_total的值不应减小。

1 个答案:

答案 0 :(得分:0)

drop table if exists t;
create table t(account_balance int,earned_amount int);

drop trigger if exists t;
delimiter $$
create trigger t before update on t
for each row
begin
        insert into debug_table(msg,msg2) values (old.earned_amount,new.earned_amount);
        if new.account_balance > old.account_balance then 
            set new.earned_amount = new.earned_amount + (new.account_balance - old.Account_balance);
        end if;
        insert into debug_table(msg,msg2) values (old.earned_amount,new.earned_amount);
end $$

delimiter ;
truncate table t;
truncate table debug_table;

insert into t values (10,10);
update t set account_balance = Account_balance + 10 where 1 = 1;


update t set account_balance = Account_balance - 10 where 1 = 1;

select * from t;

+-----------------+---------------+
| account_balance | earned_amount |
+-----------------+---------------+
|              10 |            20 |
+-----------------+---------------+
1 row in set (0.00 sec)

select * from debug_table;

+----+------+------+
| id | msg  | MSG2 |
+----+------+------+
|  1 | 10   | 10   |
|  2 | 10   | 20   |
|  3 | 20   | 20   |
|  4 | 20   | 20   |
+----+------+------+
4 rows in set (0.00 sec)

注意debug_table对解决方案不是必需的,它表明mysql要做的第一件事是写所有OLD。新值。值。

我个人不会存储earned_amount,错误的范围很大,并且可以轻松计算出来。例如,假设有一个正数被抵消/冲销,这会减少赚取的金额,但是没有办法将其与实际提款区分开。