回答編集履歴

1

trigger sample

2017/09/22 06:52

投稿

yambejp
yambejp

スコア114968

test CHANGED
@@ -23,3 +23,67 @@
23
23
  ただしあまり大量のデータをトランザクションで保持するのはどうかとおもうので
24
24
 
25
25
  毎回テストするような運用は避けたほうがいいかもしれません
26
+
27
+
28
+
29
+ # sample trigger
30
+
31
+ テーブル作成
32
+
33
+ ```SQL
34
+
35
+ create table tblA(aid int not null primary key auto_increment,val1 int,val2 varchar(10));
36
+
37
+ create table tblB(bid int not null primary key auto_increment,aid int not null,val1 int,val2 varchar(10),tbla_modified datetime);
38
+
39
+ ```
40
+
41
+ トリガー作成
42
+
43
+ ```SQL
44
+
45
+ drop trigger if exists trg_a ;
46
+
47
+ delimiter //
48
+
49
+ create trigger trg_a after update on tblA
50
+
51
+ for each row begin
52
+
53
+ insert into tblB(aid,val1,val2,tbla_modified) values(OLD.aid,OLD.val1,OLD.val2,NOW());
54
+
55
+ end;
56
+
57
+ //
58
+
59
+ delimiter ;
60
+
61
+ ```
62
+
63
+ データ投入
64
+
65
+ ```SQL
66
+
67
+ insert into tblA(val1,val2) values(10,'test1'),(20,'test2'),(30,'test3'),(30,'test4');
68
+
69
+ ```
70
+
71
+ ※triggerはtblAのupdateを元にするのでinsert時にはtblBに影響はない
72
+
73
+ データ更新
74
+
75
+ ```SQL
76
+
77
+ update tblA set val2='test5' where val1=30;
78
+
79
+ ```
80
+
81
+ ※tblAの更新された行を元にtblBにtblAの古いデータが保持され、更新された時間が記載される
82
+
83
+
84
+
85
+ なので、tblAを元に戻したいのであれば更新日時をキーにtblBからtblAにデータを
86
+
87
+ 流し込めばよい
88
+
89
+