对于表付款中的每个用户名,我应该分别向payment_amount
表 total_balance 中插入total_money
的总和,每次自动插入当表 Payments
例如: 用户“ John”用2次100 $和50 $填充了他的帐户,帐户中的总计150 $
表格示例:
表格:付款
ID username payment_amount Status
+-------+-------------+-------------+-----------+
| 1 | John | 100 | Complete |
+-------+-------------+-------------+-----------+
| 2 | John | 50 | Complete |
+-------+-------------+-------------+-----------+
| 3 | Alex | 100 | Complete |
+-------+-------------+-------------+-----------+
表格:总余额
ID username total_money
+-------+-------------+-------------+
| 1 | John | 150 |
+-------+-------------+-------------+
| 2 | Alex | 100 |
+-------+-------------+-------------+
此处已回答我的问题,但我无法将触发器配置为适用于上述表格 Here Solved 1-answer
答案 0 :(得分:0)
您应该在https://dev.mysql.com/doc/refman/8.0/en/triggers.html上阅读mysql触发器。在这个问题中,触发代码很简单。
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)
请注意使用不平衡余额检查和使用NEW。列(请参见手册)