CREATE TABLE `t1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `ts` timestamp(6) GENERATED ALWAYS AS ROW START, `te` timestamp(6) GENERATED ALWAYS AS ROW END, PRIMARY KEY (`id`,`te`), PERIOD FOR SYSTEM_TIME (`ts`, `te`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 WITH SYSTEM VERSIONING; 注意看红色字体,这就是新增加的语法,字段ts和te是数据变化的起止时间和结束时间。
另外用ALTER TABLE更改表结构,语法如下:
ALTER TABLE t1 ADD COLUMN ts TIMESTAMP(6) GENERATED ALWAYS AS ROW START, ADD COLUMN te TIMESTAMP(6) GENERATED ALWAYS AS ROW END, ADD PERIOD FOR SYSTEM_TIME(ts, te), ADD SYSTEM VERSIONING; 二、查询历史数据 这里我们做一个实验,首先要插入1条数据,
接着把姓名为“张三”,改成“李四”(误更改数据)
现在数据已经成功变更,那么我想查看历史数据怎么办呢?非常简单,一条命令搞定。
语法一:查询一小时内的历史数据。 SELECT * FROM t FOR SYSTEM_TIME BETWEEN (NOW() - INTERVAL 1 HOUR) AND NOW(); HOUR:小时 MINUTE:分钟 DAY:天 MONTH:月 YEAR:年
语法二:查询一段时间内的历史数据 SELECT * FROM t1 FOR SYSTEM_TIME FROM '2018-05-15 00:00:00' TO '2018-05-15 14:00:00';
语法三:查询所有历史数据 SELECT * FROM t1 FOR SYSTEM_TIME ALL;
三、恢复历史数据 现在我们已经找到了历史数据“张三”,只需把它导出来做恢复即可。
SELECT id,name FROM t1 FOR SYSTEM_TIME ALL where id = 1 AND name = '张三' into outfile '/tmp/t1.sql' / FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'; FIELDS TERMINATED BY ',' --- 字段的分隔符 OPTIONALLY ENCLOSED BY '"' --- 字符串带双引号
导入恢复
load data infile '/tmp/t1.sql' replace into table t1 / FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' / (id,name);