Test Table 1
DROP TABLE IF EXISTS test; CREATE TABLE test ( id bigint(11) unsigned NOT NULL AUTO_INCREMENT, name varchar(100) NOT NULL DEFAULT '', type varchar(100), create_time datetime, PRIMARY KEY (ID) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Test Table 2
Drop table if exists test_hisy; create table test_hisy (id bigint (11) unsigned not null AUTO_INCREMENT, name varchar (100) not null default '', type varchar (100), create_time datetime, operation varchar (100) COMMENT 'Operation type', primary key (ID) ENGINE = InnoDB AUTO_INCREMENT = 1 default charset = utf8;
Insert trigger
AFTER adding a record to table test, INSERT the record with the type Value of "1" to the table test_hisy at the same time (after insert: triggered AFTER input, before insert: triggered BEFORE input)
DELIMITER //DROP TRIGGER IF EXISTS t_after_insert_test//CREATE TRIGGER t_after_insert_testAFTER INSERT ON testFOR EACH ROWBEGIN IF new.type='1' THEN insert into test_hisy(name, type, create_time, operation) values(new.name, new.type, new.create_time, 'insert'); END IF;END;//
Update trigger
When the table test is modified, if the type value is "2", the records BEFORE modification are inserted to the test_hisy table at the same time (after update: triggered AFTER modification, before update: triggered BEFORE modification)
DELIMITER //DROP TRIGGER IF EXISTS t_before_update_test//CREATE TRIGGER t_before_update_testBEFORE UPDATE ON testFOR EACH ROWBEGIN IF new.type='2' THEN insert into test_hisy(name, type, create_time, operation) values(old.name, old.type, old.create_time, 'update'); END IF;END;//
Delete trigger
BEFORE the table test deletes a record, the deleted record is input to the table test_hisy (triggered after delete: triggered AFTER deletion, before delete: triggered BEFORE deletion)
DELIMITER //DROP TRIGGER IF EXISTS t_before_delete_test//CREATE TRIGGER t_before_delete_testBEFORE DELETE ON testFOR EACH ROWBEGIN insert into test_hisy(name, type, create_time, operation) values(old.name, old.type, old.create_time, 'delete');END;//
Note: In the above trigger example, the new is the modified data, and the old is the data before the modification.