0

I am new to SQL and I don't know where to get help. I faced a problem while using the trigger, but it doesn't response. This is my code here:

DELIMITER $$

CREATE TRIGGER payments_after_insert AFTER INSERT ON payments
FOR EACH ROW BEGIN UPDATE invoices SET payment_total = payment_total + NEW.amount WHERE invoice_id = NEW.invoice_id; END $$

DELIMITER ;

Here is the second part:

INSERT INTO payments                                        
VALUES (DEFAULT, 5, 3, '2019-01-01', 10, 1)

I execute the first part, then the second. Strangely the new data has been inserted, but the triggers don't.

Can someone help me? I have been searching for the answers for few days and I don't know how to solve it.

Thank you in advance.

Akina
  • 19,866
  • 2
  • 17
  • 21
  • Provide complete scripts pack (CREATE TABLE, INSERT INTO with some sample data) which allows to reproduce your task completely. – Akina Nov 14 '23 at 09:14

1 Answers1

0

A model:

-- sample structures and data
CREATE TABLE payments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  column1 INT,
  column2 INT,
  somedate DATE,
  amount INT,
  invoice_id INT
);
INSERT INTO payments VALUES 
  (DEFAULT, 5, 3, '2018-01-01', 15, 1),
  (DEFAULT, 5, 3, '2018-02-02', 55, 2);
CREATE TABLE invoices (
  invoice_id INT,
  payment_total INT
);
INSERT INTO invoices VALUES (1,15), (2,55);
SELECT * FROM invoices;
SELECT * FROM payments;
invoice_id payment_total
1 15
2 55
id column1 column2 somedate amount invoice_id
1 5 3 2018-01-01 15 1
2 5 3 2018-02-02 55 2
-- trigger (copied from the question)
CREATE TRIGGER payments_after_insert
    AFTER INSERT ON payments        
    FOR EACH ROW
BEGIN 
    UPDATE invoices 
    SET payment_total = payment_total + NEW.amount
    WHERE invoice_id = NEW.invoice_id;
END
-- insertion (copied from the question)
INSERT INTO payments                                        
VALUES (DEFAULT, 5, 3, '2019-01-01', 10, 1)
-- looking for final data state
SELECT * FROM invoices;
SELECT * FROM payments;
invoice_id payment_total
1 25
2 55
id column1 column2 somedate amount invoice_id
1 5 3 2018-01-01 15 1
2 5 3 2018-02-02 55 2
3 5 3 2019-01-01 10 1

fiddle

Akina
  • 19,866
  • 2
  • 17
  • 21