【问题标题】:Copy to another table on mysql update在mysql更新上复制到另一个表
【发布时间】:2014-01-04 06:32:17
【问题描述】:

我有一个 mysql 表,每当有添加、修改/更新或删除时,我都想获取该行并将其添加到“存档”表中(在更新或删除之前)。这是一个历史档案(即发生了什么)。有没有办法在数据库层“自动”做到这一点?有没有更好的办法...

【问题讨论】:

标签: mysql mariadb


【解决方案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 发出以下 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 将包含

|表1_ID |第 1 列 | |-----------|---------| | 1 |价值11 |

table1_history 将包含

| HISTORY_ID | DT |操作 |表1_ID |第 1 列 | |------------|--------------------------------|--- --------|------------|---------| | 1 | 2014 年 1 月 4 日 06:31:15+0000 |插入 | 1 |值1 | | 2 | 2014 年 1 月 4 日 06:31:15+0000 |插入 | 2 |值2 | | 3 | 2014 年 1 月 4 日 06:31:15+0000 |更新 | 1 |价值11 | | 4 | 2014 年 1 月 4 日 06:31:15+0000 |删除 | 2 |值2 |

这里是SQLFiddle演示

【讨论】:

  • @Trythis 我认为这是您问题的最佳答案
【解决方案2】:

尝试使用触发器

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;

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 2016-01-31
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多