'TRIGGER AFTER UPDATE - copy to another table
I would like to create a TRIGGER AFTER UPDATE which copy the row that has just been updated in TABLE_1 to the TABLE_2.
This code raise an error after updated more than one row : SQL Error (1062): Duplicate entry '1' for key 'PRIMARY'
I know this code is not right but I just don't know how to manipulate the row that has been updated.
CREATE DEFINER=`companyERP`@`%` TRIGGER `trigger` AFTER INSERT ON `Table_1`
FOR EACH ROW BEGIN
INSERT INTO Table_2 SELECT *
FROM Table_1;
END
Solution 1:[1]
CREATE DEFINER=`companyERP`@`%` TRIGGER `trigger` AFTER INSERT ON `Table_1`
FOR EACH ROW BEGIN
INSERT INTO Table_2 SELECT new.Field1, newField2 ...
FROM Table_1
END
Solution 2:[2]
Try:
/*
CREATE DEFINER=`companyERP`@`%` TRIGGER `trigger` AFTER INSERT ON `Table_1`
FOR EACH ROW BEGIN
INSERT INTO Table_2 SELECT *
FROM Table_1;
END
*/
DELIMITER //
CREATE TRIGGER `trigger` AFTER UPDATE ON `Table_1`
FOR EACH ROW
BEGIN
INSERT INTO `Table_2`
(`id_table_1`, `old_value`, `created_at`)
VALUES
(OLD.`id`, OLD.`value`, NOW());
END//
DELIMITER ;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | H.K |
| Solution 2 | wchiquito |
