在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 ;