1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mysqlで直近のバックアップと現在の値を比較

Last updated at Posted at 2016-01-07

以下のようなテーブル構成


  • 業務テーブル(USER_TABLE)
カラム 備考
USER_ID INT ユーザID(PK)
USER_INFO_1 VARCHAR(255) ユーザ情報1
USER_INFO_2 VARCHAR(255) ユーザ情報2
USER_INFO_3 VARCHAR(255) ユーザ情報3
MODIFIED TIMESTAMP 更新日時
  • バックアップテーブル (USER_BACKUP_TABLE)
カラム 備考
ID INT 連番ID(PK)
USER_ID INT ユーザID
USER_INFO_1 VARCHAR(255) ユーザ情報1
USER_INFO_2 VARCHAR(255) ユーザ情報2
USER_INFO_3 VARCHAR(255) ユーザ情報3
MODIFIED TIMESTAMP 更新日時

業務テーブルにあるユーザの現在の情報と直近のバックアップした情報の変更点を確認したいため、以下のSQLで実現できた。

サブクエリしすぎかな。。。

select 
  NOW.USER_ID,
  NOW.USER_INFO_1,
  BK.USER_INFO_1,
  NOW.USER_INFO_2,
  BK.USER_INFO_2,
  NOW.USER_INFO_3,
  BK.USER_INFO_3,
from USER_TABLE NOW 
join
  (select USER_ID, USER_INFO_1, USER_INFO_2, USER_INFO_3 from USER_BACKUP_TABLE UBT 
  join 
    (select USER_ID, MAX(ID) as last_id from USER_BACKUP_TABLE group by USER_ID WHERE CREATED bwtween '2015-12-01 00:00:00' and '2015-12-31 23:59:59') AS MAXBK
  ON UBT.USER_ID=MAXBK.USER_ID AND UBT.ID=MAXBK.ID) AS BK
ON NOW.USER_ID=BK.USER_ID
WHERE NOW.MODIFIED bwtween '2015-12-01 00:00:00' and '2015-12-31 23:59:59'
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?