插入后,MySql触发器更新选择总和

时间:2013-05-28 22:55:27

标签: mysql select triggers sum

我有三张桌子。

  1. 成员
  2. 帐户
  3. 交易
  4. 我想在将新事务插入到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
            )
    

1 个答案:

答案 0 :(得分:1)

尝试

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 演示。