MySQL使用触发器实现删除表时将数据转移到历史表

最近重新研究触发器的时候,突然想到了一个在工作中经常用到的场景,那就是有些时候我们需要对表里的数据进行删除,但是在删除的时候,需要将被数据插入到历史表中,想着用触发器实现就比较方便了。

例子中使用的表结构,被删除表的test2的表结构和它一样

-- 创建备份表
create table test2_history
(
    field1 varchar(10)   not null,
    field2 varchar(5)    not null,
    field3 int default 1 null,
    field4 decimal(4, 2) null,
    field5 int auto_increment
        primary key
);

创建触发器

-- 创建触发器
create trigger test2_trigger_delete_before
    before delete
    on test2
    for each row
begin
    -- 统计删除前test2的行数赋值到test2_befNum变量
    select count(*) from test2 into @test2_befNum;
    -- 将test2表被删除的数据,插入到test2_history历史表中
    insert into test2_history select field1,field2, field3, field4, field5 from test2 deleted;
    -- 将被删除test2表的field1字段赋值给test2_del_field1变量
    select field1 from test2 deleted into @test2_del_field1;
end ;

在这里select field1,field2,field3,field4,field5 字段顺序要和test2表的字段顺序一致,否则会有问题

此时test2_history表的数据情况

test2表的情况

执行删除test2 的操作

delete from test2;

再此查询test2_history历史表

生于忧患,死于安乐
原文地址:https://www.cnblogs.com/songlove/p/15600051.html