Coba
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;
Ini SQLFiddle demo.
PERBARUI :Karena pemicu tidak tersedia untuk Anda, coba bungkus INSERT
dan UPDATE
menjadi prosedur tersimpan seperti ini
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 ;
Dan kemudian gunakan
CALL AddTransaction(1, 10.50);
Ini SQLFiddle demo untuk skenario itu.