mysql通過觸發器實現兩個表的同步,需要了解的朋友可以看一下。
有兩張表A和B,要求往A里面插入一條記錄的同時要向B里面也插入一條記錄,向B里面插入一條記錄的同時也向A插入一條記錄。兩張表的結構不同,需要將其中幾個字段對應起來。可以用下面的觸發器實現。
表A的觸發器:
1
2
3
4
5
6
7
|
begin set @disable=1; if @disable=1 and NOT EXISTS(SELECT 1 FROM tableB where ID= new .ID) then insert into tableB (ID,對應字段1) values( new .ID, new .對應字段1); end if ; set @disable=0; end |
表B的觸發器:
1
2
3
4
5
6
7
|
begin set @disable=1; if @disable=1 and NOT EXISTS(SELECT 1 FROM tableA where ID= new .ID) then insert into tableA (ID,對應字段1) values( new .ID, new .對應字段1); end if ; set @disable=0; end |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。