Mysql触发器

📅 发布时间:2026/7/5 17:06:43 👁️ 浏览次数:
Mysql触发器
建立product表操作方式operate表要求1.定义触发器实现在产品表(product)中每多一个产品,就在操作表(operate)中记录操作方式和时间以及编号记录。​ 注操作说明标记执行delete 、insert、 update2.定义触发器实现在产品表(product)中每更新一个产品就在操作表(operate)中记录操作方式和时间以及编号记录。3.定义触发器实现在产品表(product)中每删除一个产品就在操作表(operate)中记录操作方式和时间以及编号记录。mysqlProduct表内容 :字段名 字段描述 数据类型 主键 外键 非空 唯一 自增id 产品编号 Int(10) 是 否 是 是 否name 产品功能 Varchar(20) 否 否 是 否 否func 主要功能 Varchar(50) 否 否 否 否 否com 生产厂家 Varchar(20) 否 否 是 否 否address 家庭住址 Varchar(20) 否 否 否 否 否operate表内容 :字段名 字段描述 数据类型 主键 外键 非空 唯一 自增op_id 编号 Int(10) 是 否 是 是 是op_type 操作方式 Varchar(20) 否 否 是 否 否op_time 操作时间 Varchar(20) 否 否 是 否 否- 创建触发器每次激活触发器后都会更新operate表- 创建product_after_insert_trigger- 创建product_after_update_trigger- 创建product_after_delete_trigger建product表create table product (id int(10) primary key not null,name varchar(20) not null,func varchar(50),com varchar(20) not null,address varchar(20));建operate表create table operate (op_id int(10) primary key auto_increment,op_type varchar(20) not null,op_time varchar(20) not null);创建插入触发器在product表插入新记录后更新operate表mysqlcreate trigger product_after_insert_triggerafter insert on product //指定为更新操作后触发for each row //对每一行受影响的数据执行begininsert into operate (op_type, op_time)values (insert, now());end$$创建删除触发器在product表删除记录后更新operate表mysql create trigger product_after_delete_triggerafter delete on product //指定为删除操作后触发for each rowbegininsert into operate (op_type, op_time)values (delete, now()); //now() 获取当前的时间戳end$$创建更新触发器在product表更新记录后更新operate表mysql create trigger product_after_update_triggerafter update on productfor each rowbegininsert into operate (op_type, op_time, product_id)values (update, now(), old.id);end$$测试1插入操作insert into product (id, name, com) values (1, 手机, 华为);insert into product (id, name, com) values (2, 电脑, 联想);//验证插入操作记录select * from operate where op_type insert;测试2:删除操作delete from product where id 1;delete from product where id 2;//验证删除操作记录