Using MySQL triggers to update customers balance

后端 未结 1 1181
Happy的楠姐
Happy的楠姐 2021-01-01 08:03

I need some help in understanding triggers and how they work. I have 3 tables:

Customers
Id | Balance

Inv

1条回答
  •  春和景丽
    2021-01-01 08:36

    You'll need two triggers - one for the invoice table:

    delimiter //
    CREATE TRIGGER add_invoice_to_balance AFTER INSERT ON invoices
    FOR EACH
    ROW
    BEGIN
        UPDATE Customers SET balance = balance + NEW.Amount
          WHERE Customers.id = NEW.custid;
    END;
    //
    delimiter;
    

    And one for the payment table:

    delimiter //
    CREATE TRIGGER add_payment_to_balance AFTER INSERT ON payments
    FOR EACH
    ROW
    BEGIN
        UPDATE Customers SET balance = balance - NEW.Amount
          WHERE Customers.id = NEW.custid;
    END;
    //
    delimiter ;
    

    fiddle here

    0 讨论(0)
提交回复
热议问题