MySQL option/feature to track history of changes to records

Hi, my name is Guillermo Antony Cava Nuñez, today while attending an issue at work, it happened that a user was claiming that they in fact submited information with something spelled one way but in fact in the database they submited it wrong. Long story short they changed it in the database but in order to not have these sorts of situtions occur again, the project director wanted to introduce a way to record all changes and past revisions beyond date of record changed. This lead me to dicover mysql triggers. A lass, stackover flow.

 

Guillermo Cava Nuñez

Guillermo Antony Cava Nuñez

Guillermo Cava Nunez

Guillermo Antony Cava Nunez

Guillermo Cava

Guillermo Cava Nuñez

Guillermo Antony Cava Nuñez

Guillermo Cava Nunez

Guillermo Antony Cava Nunez

Guillermo Cava

Here’s a straightforward way to do this:

First, create a history table for each data table you want to track (example query below). This table will have an entry for each insert, update, and delete query performed on each row in the data table.

The structure of the history table will be the same as the data table it tracks except for three additional columns: a column to store the operation that occured (let’s call it ‘action’), the date and time of the operation, and a column to store a sequence number (‘revision’), which increments per operation and is grouped by the primary key column of the data table.

To do this sequencing behavior a two column (composite) index is created on the primary key column and revision column. Note that you can only do sequencing in this fashion if the engine used by the history table is MyISAM (See ‘MyISAM Notes’ on this page)

The history table is fairly easy to create. In the ALTER TABLE query below (and in the trigger queries below that), replace ‘primary_key_column’ with the actual name of that column in your data table.

 

And then you create the triggers:

 

And you’re done. Now, all the inserts, updates and deletes in ‘MyDb.data’ will be recorded in ‘MyDb.data_history’, giving you a history table like this (minus the contrived ‘data_columns’ column)

 

To display the changes for a given column or columns from update to update, you’ll need to join the history table to itself on the primary key and sequence columns. You could create a view for this purpose, for example:

 

Guillermo Cava Nuñez

Guillermo Antony Cava Nuñez

Guillermo Cava Nunez

Guillermo Antony Cava Nunez

Guillermo Cava

Guillermo Cava Nuñez

Guillermo Antony Cava Nuñez

Guillermo Cava Nunez

Guillermo Antony Cava Nunez

Guillermo Cava

No Comments

Post A Comment