开发者

log mysql updates

开发者 https://www.devze.com 2022-12-27 03:37 出处:网络
I have a migration script that reads from one DB and write to a second D开发者_如何学JAVAB. I usually update the existing records. How can I log the updates like:

I have a migration script that reads from one DB and write to a second D开发者_如何学JAVAB.

I usually update the existing records. How can I log the updates like:

productID : 125
title : Product1 => test update
price : 125 => 140

This means that the productID 125 had title "Products1" and became "test" after update and had price "125" which became "140"

One thought is to read the record keep the values and then update, read again the values and the compare and log what necessary fields.

Do any other methods exist?


You could use a trigger and store the changes in another table.

From the top of my head (the following assumes that productId never will be updated);

create table main (
    `id` int not null auto_increment,
    `title` varchar(30) not null,
    `price` float not null, 
    primary key(`id`)
);

create table logger (
    `id` int not null auto_increment,
    `productId` int not null,
    `from_title` varchar(30) not null,
    `to_title` varchar(30) not null,
    `from_price` float not null,
    `to_price` float not null,
    primary key(`id`)
);

delimiter //
create trigger my_logger before update on main
begin
    insert into
        logger
    set
        `productId`=OLD.`id`,
        `from_title`=OLD.`title`,
        `to_title`=NEW.`title`,
        `from_price`=OLD.`price`,
        `to_price`=NEW.`title`;
end;//
delimiter ;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号