【问题标题】:How to make this trigger workable with my tables?如何使此触发器适用于我的表?
【发布时间】:2019-03-30 12:54:02
【问题描述】:

我应该为 Payments 表中的每个用户名分别插入 payment_amount 的总和,到 total_money 表 total_balance 每次插入新的货币时都应该自动插入表付款

例如: 用户“John”在他的帐户中填写了 2 次 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

【问题讨论】:

  • 该链接提供了一个 sqlserver 答案 - 您能否确认您正在寻找一个 MYSQL 答案。
  • @P.Salmon 在上面的链接中,我们有同样的问题,但表名和预先数据类型不同,我应该用我的表来改变触发答案
  • 你没有回答我的评论,SQLSERVER 和 MYSQL 触发器的编码方式不同,不能互换。
  • @P.Salmon 是的,我正在寻找 MYSQL 答案
  • @P.Salmon 如果你可以为我的上述问题创建这样的触发器,你能帮我吗?

标签: mysql database-trigger


【解决方案1】:

您应该在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。列(见手册)

【讨论】:

  • 谢谢兄弟,上帝保佑你!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2016-12-24
相关资源
最近更新 更多