mysql trigger history table

Поддержка для триггеров включена, начиная с MySQL 5.0.2.

Когда нужно историчность данных



CREATE TABLE `user` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(255) NULL DEFAULT NULL,
	`password` CHAR(32) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=0
;





CREATE TABLE `user_history` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`user_id` INT(11) NULL DEFAULT NULL,
	`name` VARCHAR(255) NULL DEFAULT NULL,
	`password` CHAR(32) NULL DEFAULT NULL,
	`date_changed` DATETIME NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=0
;






CREATE DEFINER=`root`@`%` TRIGGER `history` BEFORE UPDATE ON `user` FOR EACH ROW BEGIN

INSERT INTO user_history 
SELECT NULL, h.*, NOW() FROM user h WHERE id = OLD.id;


END