gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:39:10 25 4
gpt4 key购买 nike

经过几次谷歌搜索,我来到了这里。

我有一个名为users的MYSQL数据库表。我有两列,account_balanceearned_total

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

记住当用户退出时,earned_total值不应减少。

最佳答案

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。值新。值。

我个人不会存储earn_amount,误差范围很大,而且很容易计算。想象一下,例如,正金额被对立/逆转,这应该会减少赚取的金额,但无法将其与实际提款区分开来。

关于mysql - 创建触发器以添加列数据但不减去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com