Using MySQL triggers to log all table changes to a secondary table

前端 未结 1 701
余生分开走
余生分开走 2020-12-02 05:52

I have a table:

CREATE TABLE `data_table` (
`data_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`field1` INT NOT NULL ,
`field2` INT NOT NULL ,
`field3` INT          


        
相关标签:
1条回答
  • 2020-12-02 06:23

    The insert syntax is

    INSERT INTO table (columns_list) VALUES (values_list)
    

    so your insert would look something like this (i'm not a MySQL expert but you can fit the query):

    INSERT INTO data_tracking 
    (`data_id` , `field` , `old_value` , `new_value` , `modified` ) 
    VALUES 
    (NEW.data_id, 'field1', OLD.field, NEW.field, CURRENT_DATETIME());
    

    And repeat it for variation on field2 and field3

    I think this would be the complete trigger, please try:

    DELIMITER $$
    
    DROP TRIGGER `update_data `$$
    
    CREATE TRIGGER `update_data` AFTER UPDATE on `data_table`
    FOR EACH ROW
    BEGIN
        IF (NEW.field1 != OLD.field1) THEN
            INSERT INTO data_tracking 
                (`data_id` , `field` , `old_value` , `new_value` , `modified` ) 
            VALUES 
                (NEW.data_id, "field1", OLD.field1, NEW.field1, NOW());
        END IF;
        IF (NEW.field2 != OLD.field2) THEN
            INSERT INTO data_tracking 
                (`data_id` , `field` , `old_value` , `new_value` , `modified` ) 
            VALUES 
                (NEW.data_id, "field2", OLD.field2, NEW.field2, NOW());
        END IF;
        IF (NEW.field3 != OLD.field3) THEN
            INSERT INTO data_tracking 
                (`data_id` , `field` , `old_value` , `new_value` , `modified` ) 
            VALUES 
                (NEW.data_id, "field3", OLD.field3, NEW.field3, NOW());
        END IF;
    END$$
    
    DELIMITER ;
    
    0 讨论(0)
提交回复
热议问题