【发布时间】:2014-01-04 06:32:17
【问题描述】:
我有一个 mysql 表,每当有添加、修改/更新或删除时,我都想获取该行并将其添加到“存档”表中(在更新或删除之前)。这是一个历史档案(即发生了什么)。有没有办法在数据库层“自动”做到这一点?有没有更好的办法...
【问题讨论】:
我有一个 mysql 表,每当有添加、修改/更新或删除时,我都想获取该行并将其添加到“存档”表中(在更新或删除之前)。这是一个历史档案(即发生了什么)。有没有办法在数据库层“自动”做到这一点?有没有更好的办法...
【问题讨论】:
您需要一组涵盖所有操作(插入、更新、删除)的触发器。
假设你有一张桌子
CREATE TABLE table1
(
table1_id int not null auto_increment primary key,
column1 varchar(32)
);
您为它创建了以下历史记录表
CREATE TABLE table1_history
(
history_id int not null auto_increment primary key,
dt datetime not null,
operation varchar(6) not null,
table1_id int not null,
column1 varchar(32) not null
);
现在你的触发器可能看起来像
CREATE TRIGGER tg_ai_table1
AFTER INSERT ON table1
FOR EACH ROW
INSERT INTO table1_history (dt, operation, table1_id, column1)
VALUES(NOW(), 'insert', NEW.table1_id, NEW.column1);
CREATE TRIGGER tg_au_table1
AFTER UPDATE ON table1
FOR EACH ROW
INSERT INTO table1_history (dt, operation, table1_id, column1)
VALUES(NOW(), 'update', NEW.table1_id, NEW.column1);
CREATE TRIGGER tg_bd_table1
BEFORE DELETE ON table1
FOR EACH ROW
INSERT INTO table1_history (dt, operation, table1_id, column1)
VALUES(NOW(), 'delete', OLD.table1_id, OLD.column1);
如果我们针对 table1 发出以下 DML 语句
INSERT INTO table1 (column1) VALUES ('value1'), ('value2');
UPDATE table1 SET column1 = 'value11' WHERE table1_id = 1;
DELETE FROM table1 WHERE table1_id = 2;
table1 将包含
table1_history 将包含
这里是SQLFiddle演示
【讨论】:
尝试使用触发器
eg:
DROP TRIGGER auditlog
CREATE TRIGGER auditlog BEFORE UPDATE ON frequencies
FOR EACH ROW BEGIN
INSERT INTO frequencies_audit select * from frequencies where freqId = NEW.freqId;
END;
【讨论】: