4

我有三张桌子。

  1. 成员
  2. 账户
  3. 交易

在将新事务插入 Transactions 表后,我想用所有 Transactions.TransactionAmount 的总和更新 Accounts.AccountBalance。

以下代码似乎对我不起作用。有什么建议么?

CREATE TRIGGER NewTrigger
    AFTER INSERT ON Transactions
    FOR EACH ROW 
    BEGIN
        UPDATE Accounts SET Accounts.AccountBalance = (
                SELECT SUM(Transactions.TransactionAmount) 
                    FROM Transactions
                    WHERE Accounts.AccountID=Transactions.AccountID
        )
4

1 回答 1

2

尝试

CREATE TRIGGER NewTrigger 
AFTER INSERT ON Transactions
FOR EACH ROW
UPDATE Accounts a
   SET a.AccountBalance = 
    (SELECT SUM(TransactionAmount) 
       FROM Transactions
      WHERE AccountID = a.AccountID)
 WHERE a.AccountID = NEW.AccountID;

这是SQLFiddle演示。

更新:由于您无法使用触发器,因此请尝试包装INSERTUPDATE进入这样的存储过程

DELIMITER $$
CREATE PROCEDURE AddTransaction(IN aid INT, amount DECIMAL(11, 2)) 
BEGIN
  START TRANSACTION;
  INSERT INTO Transactions (AccountID, TransactionAmount)
  VALUES (aid, amount);
  UPDATE Accounts a
     SET a.AccountBalance = 
      (SELECT SUM(TransactionAmount) 
         FROM Transactions
        WHERE AccountID = a.AccountID)
   WHERE a.AccountID = aid;
   COMMIT;
END $$
DELIMITER ;

然后使用它

CALL AddTransaction(1, 10.50);

这是该场景的SQLFiddle演示。

于 2013-05-28T23:03:42.730 回答