如何使这个触发器适用于我的表?

How to make this trigger workable with my tables?

我应该为每个用户名分别插入 payment_amount 的总和,从 table Payments,到 total_money table total_balance 每次插入新值时都会自动插入 table Payments

例如:用户"John"在他的账户中填充了2次100$和50$,他的账户总计150 $

table 中的示例:

Table:付款

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

Table: total_balance

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

这里回答了我的问题,但我无法将触发器配置为适用于上述 tables

您应该在此处阅读 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 的使用。列(参见手册)