質問するログイン新規登録

回答編集履歴

1

調整

2018/11/20 09:02

投稿

yambejp
yambejp

スコア118110

answer CHANGED
@@ -1,4 +1,34 @@
1
1
  カラムXはAが更新されたときに必ず更新されるのでしょうか?
2
2
  カラムXがdateでは更新を細かく確認できないですよね
3
3
  timestamp(datetime)にすればcopyAのカラムXの最大値より大きなカラムXをもつAの
4
- データを抽出すればよいでしょう
4
+ データを抽出すればよいでしょう
5
+
6
+ # sample
7
+ ```SQL
8
+ create table tbl_a1(c1 varchar(20) not null primary key,c2 varchar(20),cx datetime default current_timestamp on update current_timestamp);
9
+ create table tbl_a2(c1 varchar(20) not null primary key,c2 varchar(20),cx datetime);
10
+ insert into tbl_a1 values('x001','y001','2018-11-01 00:00'),('x002','y002','2018-11-01 00:00'),('x003','y003','2018-11-01 00:00');
11
+ insert into tbl_a2 values('x001','y001','2018-11-01 00:00'),('x002','y002','2018-11-01 00:00'),('x003','y003','2018-11-01 00:00');
12
+ ```
13
+ とりあえず同期されている状態にします。
14
+ ここからa1のデータをいじるとして
15
+ ```SQL
16
+ update tbl_a1 set c2='y002x' WHERE c1 = 'x002';
17
+ delete from tbl_a1 where c1=('x003');
18
+ insert into tbl_a1(c1,c2) values('x004','y004');
19
+ ```
20
+ x002は更新されてcxが現在の日時に、x004のデータは新規データです
21
+ x003は削除なのでa1にデータが残りません
22
+ このデータをa1→a2にするには
23
+
24
+ ```SQL
25
+ insert into tbl_a2
26
+ select * from tbl_a1 where cx>(select max(cx) from tbl_a2)
27
+ on duplicate key update c2=values(c2),cx=values(cx)
28
+ ```
29
+ とします。
30
+ 削除分まで同期する場合は
31
+ ```SQL
32
+ delete from tbl_a2 where not exists(select 1 from tbl_a1 where tbl_a2.c1=c1)
33
+ ```
34
+ も実行しておいてください