6

Mysql 数据变动备份

 3 years ago
source link: https://arminli.com/mysql-backup/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Armin's Blog

Mysql 数据变动备份

June 06, 2018

本文保存 Mysql 数据库变动的思路是把变动(前或后)的数据保存到一个新的表中。

假如原表名为 tablename,创建一个新表命名为 history_table,其中字段都跟 tablename 一致,创建一个触发器命名为 trigger1,在每次更新后都把新的数据插入到备份表中,这样就知道每次数据库做了哪些改动:

CREATE TRIGGER `trigger1`
AFTER UPDATE ON `tablename`
FOR EACH ROW
    INSERT INTO history_table
    VALUES
    (
        NEW.field1,
        NEW.field2
    );

把里面的 field1, field2 换成自己表中的字段即可。

也可以在 phpmyadmin 中直接创建 trigger,

225 trigger

直接在定义中写入

INSERT INTO history_table
VALUES
(
    NEW.field1,
    NEW.field2
);

可能会有的问题是,如果原表主键是数字,那么修改原表这一行一次以上的话,备份表就会出现两行相同的主键数据。我们可以在备份表中另建一个主键来解决。

Reference

  1. https://kahimyang.com/kauswagan/code-blogs/552/create-history-record-for-every-change-in-mysql-table-audit-trail-mysql-trigger

Profile picture

Written by Armin Li , a venture capitalist. [Weibo] [Subscribe]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK