通过示例最容易解释。这是我创建触发器的 MySQL 查询:
DELIMITER $$
DROP TRIGGER IF EXISTS `tblExample_UPDATE`$$
CREATE TRIGGER `tblExample_UPDATE` AFTER UPDATE ON `tblExample`
FOR EACH ROW
BEGIN
IF (NEW.field1 != OLD.field1) THEN
INSERT INTO tblChanges (object_type,object_id,change_type,field_name,field_before,field_after,log_time) VALUES ("example",NEW.id,"edited","field1",OLD.field1,NEW.field1,NOW());
END IF;
IF (NEW.field2 != OLD.field2) THEN
INSERT INTO tblChanges (object_type,object_id,change_type,field_name,field_before,field_after,log_time) VALUES ("example",NEW.id,"edited","field2",OLD.field2,NEW.field2,NOW());
END IF;
IF (NEW.field3 != OLD.field3) THEN
INSERT INTO tblChanges (object_type,object_id,change_type,field_name,field_before,field_after,log_time) VALUES ("example",NEW.id,"edited","field3",OLD.field3,NEW.field3,NOW());
END IF;
.
..
...
..
.
IF (NEW.field1337 != OLD.field1337) THEN
INSERT INTO tblChanges (object_type,object_id,change_type,field_name,field_before,field_after,log_time) VALUES ("example",NEW.id,"edited","field1337",OLD.field1337,NEW.field1337,NOW());
END IF;
END$$
DELIMITER ;
所以基本上我正在逐个字段地检查更改。它确实有效,但将成为一个需要维护的 PITA,因为任何架构更改都会导致问题。
有没有办法以某种方式遍历每个字段而不是单独检查每个字段?