在一个触发器中更新2个表

时间:2014-09-18 14:40:58

标签: mysql sql database triggers

请查看以下触发器

DELIMITER $$
CREATE TRIGGER `Transactions_AINS` AFTER INSERT ON `Transactions` 
FOR EACH ROW
    UPDATE Portfolio 
    SET Invest_Amount = Invest_Amount + NEW.Transaction_Amount
    WHERE idPortfolio = NEW.idPortfolio

在我的Transactions表中,还有另一个名为Balance的字段。它也等于Invest_Amount + NEW.Transaction_Amount。那么,如何在同一个Trigger中更新此列?

2 个答案:

答案 0 :(得分:0)

我认为以下内容应该有效,但我承认我从未在触发器中试过这个:

DELIMITER $$
CREATE TRIGGER `Transactions_AINS` AFTER INSERT ON `Transactions` 
FOR EACH ROW
    UPDATE Portfolio , Balance
    SET Portfolio.Invest_Amount = Portfolio.Invest_Amount + NEW.Transaction_Amount,
Balance.Invest_Amount = Balance.Invest_Amount + NEW.Transaction_Amount
    WHERE Portfolio.idPortfolio = NEW.idPortfolio and Balance.idPortfolio = NEW.idPortfolio

答案 1 :(得分:0)

使用开始和结束关键字在同一触发器中执行更多语句。

DELIMITER $$
CREATE TRIGGER `Transactions_AINS` AFTER INSERT ON `Transactions` 
FOR EACH ROW
    BEGIN
        UPDATE Portfolio 
        SET Invest_Amount = Invest_Amount + NEW.Transaction_Amount
        WHERE idPortfolio = NEW.idPortfolio;
        UPDATE Transactions t SET Balance =
             (SELECT Invest_Amount FROM Portfolio WHERE idPortfolio = t.idPortFolio)
        WHERE idTransactions = NEW.idTransactions;
    END; $$