gpt4 book ai didi

mysql - 如何使该触发器适用于我的表?

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

我应该为每个用户名从表Payments中分别插入 payment_amount总和到total_moneytotal_balance每次将新金额插入表 Payments

时都应自动插入

例如:用户“John”在他的帐户中两次充值 100$ 和 50$,他的帐户总计 150$

表格中的示例:

表:付款

 ID      username     payment_amount    Status  
+-------+-------------+-------------+-----------+
| 1 | John | 100 | Complete |
+-------+-------------+-------------+-----------+
| 2 | John | 50 | Complete |
+-------+-------------+-------------+-----------+
| 3 | Alex | 100 | Complete |
+-------+-------------+-------------+-----------+

表:total_balance

 ID      username      total_money      
+-------+-------------+-------------+
| 1 | John | 150 |
+-------+-------------+-------------+
| 2 | Alex | 100 |
+-------+-------------+-------------+

这里回答了我的问题,但我无法将触发器配置为适用于上面的表格 Here Solved 1-answer

最佳答案

您应该在这里阅读 mysql 触发器 https://dev.mysql.com/doc/refman/8.0/en/triggers.html 。在这个问题中,触发代码很简单。

drop table if exists t,t1;
create table t(id int auto_increment primary key,name varchar(20),balance int);
create table t1(id int auto_increment primary key, tid int, amount int);
drop trigger if exists t;
delimiter $$
create trigger t after insert on t1
for each row
begin
update t
set balance = ifnull(balance,0) + new.amount
where t.id = new.tid;
end $$

delimiter ;

insert into t (name) values ('john'),('paul');
insert into t1 (tid,amount) values
(1,10),(1,10),
(2,30);

select * from t1;
+----+------+--------+
| id | tid | amount |
+----+------+--------+
| 1 | 1 | 10 |
| 2 | 1 | 10 |
| 3 | 2 | 30 |
+----+------+--------+
3 rows in set (0.00 sec)
select * from t;

+----+------+---------+
| id | name | balance |
+----+------+---------+
| 1 | john | 20 |
| 2 | paul | 30 |
+----+------+---------+
2 rows in set (0.00 sec)

请注意对余额进行 isnull 检查的使用以及 NEW 的使用。列(参见手册)

关于mysql - 如何使该触发器适用于我的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55431632/

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