我有一个mysql表,每当有添加,修改/更新或删除时,我想取行并将其添加到“存档”表(在更新或删除之前)。这是一个历史档案(即发生了什么)。有没有办法在“自动”数据库层中执行此操作?有更好的方法......
答案 0 :(得分:1)
您需要一组涵盖所有操作的触发器(插入,更新,删除)。
假设你有一张桌子
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
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_ID | COLUMN1 | |-----------|---------| | 1 | value11 |
table1_history
将包含
| HISTORY_ID | DT | OPERATION | TABLE1_ID | COLUMN1 | |------------|--------------------------------|-----------|-----------|---------| | 1 | January, 04 2014 06:31:15+0000 | insert | 1 | value1 | | 2 | January, 04 2014 06:31:15+0000 | insert | 2 | value2 | | 3 | January, 04 2014 06:31:15+0000 | update | 1 | value11 | | 4 | January, 04 2014 06:31:15+0000 | delete | 2 | value2 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
尝试使用触发器
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;