简体   繁体   中英

How to store different version of data in a relational database?

Here is the example, for example, I have a table called Profile , and have different columns like:

id, firstName, secondName, address

typically, I create a profile, full in the information, and the database will become something like this:

 1| Ted | WONG | Hong Kong |

after that, I may update the data, like this

 1| Ted | WONG | US |

the data Hong Kong will be changed by an UPDATE SQL command, and I lose track of previous data. So, is there any way to let the database keep track of previous data and maintain the current information? Thanks.

Add a version number column that you increase with each update but retain the same id. Then when retrieving the latest row for a given id you need to do a

where versionNo = (select max(versionNo) from table where id = <outerTableAliasOrVariable>.id)

Add a "Version" column as the first column of every table that you want to track versions, and their child tables. The column should be added to your clustered primary key as the first column. The current version should always have Version=0 to make writing your queries easier, and not require searching for MAX(version) on every query. Make sure that all child tables also contain the Version column and reference it in their foreign keys. Before an update, copy Version=0 data from ALL related tables to Version=1. The next update would copy to Version=2 and so forth. Eventually you would have the oldest data in Version=1, the latest in Version=0 and the newest in Version=X. This way you can make complicated database schemas, control data versions and be able to completely roll back data to a historical version by copying data from Version=X to Version=0.

In your case, your new table structure would be...

Version, id, firstName, secondName, address (PK- VersionId, id)

If you had a child table, like a transaction table, it would look like this...

Version, id, TransactionId, Amount (PK- VersionId, id, TransactionId)

I've used this method for maintaining data versions without having to make extra tables to support it.

This can be achieved by storing all historical data and having a group column:

id, firstname,secondname, address, group

then when you update the data you never ALTER it, you simply add a new revision.

So, your table will look like the following:

1, Ted, Wong, Hong Kong, 1
2, Ted, Wong, US, 1

So to retrieve the current (or last) revisions you need to select the appropriate revision:

SELECT TOP 1 * FROM <table> WHERE Group = 1 ORDER BY id DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM