我有三张桌子。
我想在将新事务插入到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
)
答案 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 演示。
更新:由于您无法使用触发器,请尝试将INSERT
和UPDATE
包装到这样的存储过程中
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 演示。