MySQL 中的触发器问题

Problems with triggers in MySQL

我必须创建 table 和触发器才能进行银行帐户移动。我做了一些,但我被困在平衡点。我有这些 table:

这里我只是插入了关于交易的信息,描述说明了我在做什么(存款 50,取款 20 等),D 表示存款,W 表示取款。

CREATE TABLE transactions
(account VARCHAR (10) NOT NULL,
date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP (),
description varchar (30) NOT NULL,
type ENUM ( 'D', 'W') NOT NULL,
value DECIMAL (7,2) NOT NULL
); 

我做了一个触发器,说明哪些用户进行了交易和其他信息。后来发现有问题

我有一个叫做余额的table,我需要有帐号和当前余额。

CREATE TABLE balance
(Account VARCHAR (10) PRIMARY KEY,
balance DECIMAL (7,2) default 0 NOT NULL 
);

所以我创建了以下触发器,但它没有执行任何操作。

DELIMITER //
CREATE TRIGGER BALANCE_AI after insert on transactions for each row 
begin 
IF NEW.type = 'D' THEN UPDATE balance SET balance = balance + new.value WHERE account = new.account  ;
ELSE UPDATE balance set balance = balance - new.value where account = new.account;
end if;
end // 
DELIMITER ; 

我不知道如何更新已确定帐户的余额或插入并更新 table 余额中的余额。

我也试过这种方式:

CREATE TRIGGER balance_AI after insert on transactions for each row 
begin 
 UPDATE balance set balance = balance + new.valor where account = new.account;
 insert into balance values (new.account,balance) ON DUPLICATE key update account = account ;
end // 
DELIMITER ;

您只能更新存在的行 - 测试余额是否存在,如果不存在则创建。

drop table if exists transactions,balance;

CREATE TABLE transactions
(account VARCHAR (10) NOT NULL,
date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP (),
description varchar (30) NOT NULL,
type ENUM ( 'D', 'W') NOT NULL,
value DECIMAL (7,2) NOT NULL
);

CREATE TABLE balance
(Account VARCHAR (10) PRIMARY KEY,
balance DECIMAL (7,2) NOT NULL
);

drop trigger if exists t;
DELIMITER //
CREATE TRIGGER t after insert on transactions for each row 
begin 
if not exists(select 1 from balance b where b.account = new.account) then
    insert into balance values (new.account,0);
end if;

IF NEW.type = 'D' THEN 
    UPDATE balance SET balance = balance + new.value WHERE account = new.account  ;
ELSE 
    UPDATE balance set balance = balance - new.value where account = new.account;
end if;
end // 
DELIMITER ; 

insert into transactions (account,description ,type ,value) values (1,'aaa','d',10);
insert into transactions (account,description ,type ,value) values (1,'aaa','d',20);
insert into transactions (account,description ,type ,value) values (1,'aaa','w',10);

select * from balance;

+---------+---------+
| Account | balance |
+---------+---------+
| 1       |   20.00 |
+---------+---------+
1 row in set (0.001 sec)