MySQL - History Tables 이력관리 / 히스토리 테이블

MySQL - History Tables

Keeping a history of your data can be immensely useful, such as for reverting silly mistakes, or for auditing purposes. This tutorial will show you a really simple way to achieve this in a generic manner that can be applied to any table. You will be able to see what data and when, as well as return to any specific revision or point in time quickly and easily.

Preparation

I am assuming you already have a dev database to work with.

Run the following statements to create a table of data that we are going to demonstrate with throghout this tutorial.

CREATE TABLE `user_comments` (
    `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
    `comment` text NOT NULL,
    `author_id` int NOT NULL,
    `modified_timestamp` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user_comments`
(`comment`, `author_id`) VALUES
("hello world", 1),
("foo bar", 2);
Copy to clipboard

If your table's don't already have the timestamp, or author fields, then I recommend that you add them. Without the timestamp field, you will only be able to go back to a specific revision number rather than a certain point in time. Without the author_id field, you will not know who made the changes.

Steps

The first thing we need to do is clone the original table's schema to create our history table.

CREATE TABLE `user_comments_history` LIKE `user_comments`;

By using a suffix of _history rather than a prefix, you keep your history tables beside the ones they track in your database list.

From this point on, there are two main ways of structuring your history tables. For both of these options, a new field will be added to the history table which will be called history_id.

In option 1, the new history_id field will be the primary key, and id in the history table will just be a data field containing the value of and referencing the ID in the main table. This has the advantage of being very simple for copying data rows to/from the history table as the data in the columns remain exactly the same.

In option 2, the id field in the history table will remain as the primary key, and a new field (history_id) will reference the id in the original table. The advantage of this is that the schema doesn't change as id remains the primary key, but you now have to move data between the id and history_id fields when moving rows. You may find this option simpler if you rename history_id to row_id or primary_table_id. I am just keeping the name the same between the two options for this tutorial.

Option 1

Run the following steps to alter the history table to how we need it.

ALTER TABLE `user_comments_history`
MODIFY COLUMN `id` INT UNSIGNED NOT NULL;

ALTER TABLE `user_comments_history` DROP PRIMARY KEY;

ALTER TABLE `user_comments_history`
ADD COLUMN `history_id` INT UNSIGNED NOT NULL;

ALTER TABLE `user_comments_history`
ADD CONSTRAINT PRIMARY KEY (`history_id`);

ALTER TABLE `user_comments_history`
MODIFY `history_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;

It seems long-winded but unfortunately adding the primary key to a new column has to be done in that many steps.

Adding A Foreign Key

It may be a good idea to add a foreign key to enforce the relationship between the history table and the rows in the original table.

ALTER TABLE `user_comments_history`
ADD CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES `user_comments`(id) ON UPDATE CASCADE ON DELETE CASCADE;

Updating A Row

Now when we wish to update a row, we need to insert into the history table first. The code below shows how to do this in a single transaction so that both have to go through or neither. We are going to change the first row's comment from hello world to hello earth.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

START TRANSACTION;

# Insert the current row into the history table
INSERT INTO `user_comments_history` (`id`, `comment`, `author_id`, `modified_timestamp`)
    SELECT
      `id` as `id`,
      `comment` as `comment`,
      `author_id` as `author_id`,
      `modified_timestamp` as `modified_timestamp`
    FROM `user_comments`
    WHERE `comment` = 'hello world';

# Now run the update
UPDATE `user_comments`
SET `comment`='hello earth'
WHERE `comment` = 'hello world';

# Commit the transaction
COMMIT;

Restoring To A Point In Time

If you know that your data was fine on the 11th of July 2016 and you want to retrieve the data from that point in time, then just use the following query (assuming we want the history of row 1 in the primary table):

SELECT * FROM `user_comments_history`
WHERE `id`= 1
AND `modified_timestamp` < "2016-11-30"
LIMIT 1
ORDER BY `modified_timestamp` DESC

However, to change back to that point in time, then run the following transaction:

START TRANSACTION;

# Insert the current row into the history table before reverting
INSERT INTO `user_comments_history` (`id`, `comment`, `author_id`, `modified_timestamp`)
    SELECT
      `id` as `id`,
      `comment` as `comment`,
      `author_id` as `author_id`,
      `modified_timestamp` as `modified_timestamp`
    FROM `user_comments`
    WHERE `id`= 1

# Now run the update
UPDATE `user_comments` dest,
(
  SELECT * FROM `user_comments_history`
  WHERE `id`= 1
  AND `modified_timestamp` < "2016-11-30"
  ORDER BY `modified_timestamp` DESC
  LIMIT 1
) src
SET
dest.comment = src.comment,
dest.author_id = dest.author_id
WHERE dest.`id`= 1;

# Commit the transaction
COMMIT;

Option 2

If you believe that the id of every table needs to be the primary key, you can do the following instead:

ALTER TABLE `user_comments_history`
ADD COLUMN `history_id` INT UNSIGNED NOT NULL;

It may be a good idea to add a foreign key to enforce the relationship between the history table and the rows in the original table.

ALTER TABLE `user_comments_history`
ADD CONSTRAINT fk_id FOREIGN KEY (history_id) REFERENCES `user_comments`(id);

Updating A Row

Now when we wish to update a row, we need to insert into the history table first. The code below shows how to do this in a single transaction so that both have to go through or neither. We are going to change the first row's comment from hello world to hello earth.

START TRANSACTION;

# Insert the current row into the history table
INSERT INTO `user_comments_history` (`history_id`, `comment`, `author_id`, `modified_timestamp`)
    SELECT `id` as `history_id`, `comment` as `comment`, `author_id` as `author_id`, `modified_timestamp` as `modified_timestamp`
    FROM `user_comments`
    WHERE `comment` = 'hello world'
;

# Update the row int he primary table
UPDATE `user_comments`
SET `comment`='hello earth'
WHERE `comment` = 'hello world';

# Commit the transaction
COMMIT;

Restoring To A Point In Time

If you know that your data was fine on the 11th of July 2016 and you want to retrieve the data from that point in time, then just use the following query (assuming we want the history of row 1 in the primary table):

SELECT * FROM `user_comments_history`
WHERE `history_id`= 1
AND `modified_timestamp` < "2016-11-30"
LIMIT 1
ORDER BY `modified_timestamp` DESC

However, to change back to that point in time, then run the following transaction:

START TRANSACTION;

# Insert the current row into the history table before reverting
INSERT INTO `user_comments_history` (`history_id`, `comment`, `author_id`, `modified_timestamp`)
    SELECT
      `id` as `history_id`,
      `comment` as `comment`,
      `author_id` as `author_id`,
      `modified_timestamp` as `modified_timestamp`
    FROM `user_comments`
    WHERE `id`= 1

# Now run the update
UPDATE `user_comments` dest,
(
  SELECT * FROM `user_comments_history`
  WHERE `history_id`= 1
  AND `modified_timestamp` < "2016-11-30"
  ORDER BY `modified_timestamp` DESC
  LIMIT 1
) src
SET
dest.comment = src.comment,
dest.author_id = dest.author_id
WHERE dest.`id`= 1;

# Commit the transaction
COMMIT;

References

Appendix

To Use A Foreign Key or Not

It may be a good idea to add a foreign key to enforce the relationship between the history table and the rows in the original table. However if you do this, then it must be the case that if you DELETE a row from the primary table, its entire history is also removed. If you need to keep the history such a situation, then do not implement the foreign key, but your application layer will need to ensure to cascade any updates that occur to the primary table's ID. Unlike the rest of the columns, you cannot let the IDs diverge because otherwise you do not know which row in the primary table that the history table relates to. Based on my experience, there is usually no reason for the ID of a row to change but its something to be aware of.

Depending on your circumstances, sometimes it is easier for rows to have a "state" field that can be altered to mark the row as "deleted" than to actually delete the row. For example if a user deletes their account, you may wish to put into a "deleted" state rather than actually removing their data. That way the data is there if the user changes their mind at a later date. Such a scenario would allow you to keep the foreign key.

 

[출처] https://blog.programster.org/mysql-history-tables

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86858
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79158
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95895
26 감석분석 작업 로그 : 감성분석(Sentiment Analysis) - 깔끔한 텍스트 방식(tidytext) : xwMOOC 자연어 처리 졸리운_곰 2019.12.24 1244
25 '애자일과 데이터 관리의 결합'··· '데이터옵스'의 정의와 주요 기술 file 졸리운_곰 2019.11.17 1684
24 데브옵스와 분석의 결합··· ‘데이터옵스’를 아시나요? file 졸리운_곰 2019.11.17 1243
23 데이터옵스(DATAOPS) 란 무엇일까? file 졸리운_곰 2019.11.17 1638
22 데이터옵스는 단순히 데이터에 대한 데브옵스가 아님니다. DataOps is NOT Just DevOps for Data file 졸리운_곰 2019.11.17 1639
21 R에서 파이썬까지…데이터과학 학습 사이트 8곳 file 졸리운_곰 2019.04.21 1759
20 [통계] prediction VS forecast file 졸리운_곰 2019.04.03 1583
19 forecast 와 prediction의 차이를 아시나요? 졸리운_곰 2019.04.03 899
18 10분만에 끝내는 데이터분석 file 졸리운_곰 2019.04.03 1867
17 처음으로 케글 데이터분석에 도전하기 : Competing on kaggle.com for the First Time file 졸리운_곰 2019.01.27 4412
16 데이터 과학자가 갖춰야 할 5가지 스킬셋 file 졸리운_곰 2018.11.11 1377
15 데이터 사이언스 괜찮은 강의들 리스트 1 file 졸리운_곰 2018.11.11 2470
14 데이터 사이언스 학습 안내 졸리운_곰 2018.11.11 1671
13 Prophet: Automatic Forecasting Procedure 자동 예측 프로시져 프로그램 /데이터분석 / 데이터 과학 file 졸리운_곰 2018.09.04 1316
12 데이터 분석 어디에 집중할 것인가? 가장 먼저 실험에 집중하라 file 졸리운_곰 2018.02.06 1404
11 빅데이터 융합기획전문가 1기 교육 표창장 file 졸리운_곰 2018.01.03 1317
10 빅 데이터 기획에 대한 이해 file 졸리운_곰 2017.12.09 2024
9 분야별 빅데이터 애널리틱스 적용 사례 및 성공의 비결 file 졸리운_곰 2017.12.08 2161
8 하둡 에코시스템을 활용한 Hybrid DW 구축 사례 file 졸리운_곰 2017.12.08 2005
7 gmail 수신 메일로 워드클라우드 생성 : Creating a gmail wordcloud 졸리운_곰 2017.11.20 1893
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED