1. 程式人生 > >MySQL用觸發器同步兩張表

MySQL用觸發器同步兩張表

在MySQL環境下面,建立相關觸發器,在兩個表之間相關sql,希望能幫到大家

1.建person表

CREATE TABLE `person` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(256) DEFAULT NULL,
  `sex` char(16) DEFAULT NULL
) 


建person_ex
CREATE TABLE `person_ex` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(256) DEFAULT NULL,
  `sex` char(16) DEFAULT NULL
) 


2.實現的目標當person新增一條記錄,更新一條記錄或者刪除一條記錄,person_ex中sex欄位為M的記錄跟著改變

sql程式碼如下:

建立插入觸發器

create trigger person_trigger AFTER insert on person  for each row 
begin set @x = "hello trigger";
IF new.sex = 'M'
THEN
       INSERT INTO person_ex(id,name,sex) VALUES (New.id,new.`name`,new.sex);
END IF;
end; 

建立更新觸發器:
create trigger person_trigger_update AFTER UPDATE on person  for each row 
begin set @x = "trigger UPDATE";
IF new.sex = 'M'
THEN
DELETE from person_ex where person_ex.id = new.id;
       INSERT into person_ex SELECT * from person where person.id = new.id;
END IF;
end; 


建立刪除觸發器:
create trigger person_trigger_delete AFTER DELETE on person  for each row 
begin set @x = "trigger DELETE";
       DELETE FROM person_ex where person_ex.id = old.id;
end; 



3.測試SQL程式碼:

INSERT into person (id,name,sex) VALUES (1,'chigo','M')


INSERT into person (id,name,sex) VALUES (2,'Tony','F')

update person set name = 'vara' , sex = 'F' where id = 1

update person set name = 'Tony' , sex = 'M' where id = 1


update person set name = 'vara' , sex = 'M' where id = 1
DELETE from person where id = 1
INSERT into person_ex SELECT * from person where person.id = 1
update person set name = 'vara' , sex = 'F' where id = 1