如何使这个触发器与我的表一起使用?

问题描述 投票:0回答:1

我应该从表付款中为每个用户名单独插入payment_amount的总和,到total_money表total_balance每当新的velues插入表付款时应该自动插入

例如:用户“John”在他的账户150美元中填写了他的账户2次100美元和50美元,Total

表中的示例:

表:付款

 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 mysqli database-trigger
1个回答
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)

请注意使用isnull检查余额和使用NEW。专栏(见手册)

© www.soinside.com 2019 - 2024. All rights reserved.