码迷,mamicode.com
首页 > 数据库 > 详细

How to Create Triggers in MySQL

时间:2018-11-03 12:40:47      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:poi   after   inf   tiny   ESS   innodb   value   ima   sign   

https://www.sitepoint.com/how-to-create-mysql-triggers/

 

I created two tables:

CREATE TABLE `sw_user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT ‘‘,
`mobile` varchar(50) DEFAULT ‘‘,
`sex` tinyint(4) DEFAULT 0,
`address` varchar(255) DEFAULT ‘‘,
`status` tinyint(4) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;

 

CREATE TABLE `sw_log`  (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `t_name` varchar(50) DEFAULT ‘‘,
  `t_id` int(11) unsigned DEFAULT 0,
  `t_flag` tinyint(4) unsigned DEFAULT 1,
  `status` tinyint(4) unsigned DEFAULT 1,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;

 

I created three triggers:

CREATE TRIGGER `sw_user_insert` AFTER INSERT ON `sw_user` FOR EACH ROW BEGIN
INSERT INTO sw_log(t_name, t_id, t_flag) values(sw_user, NEW.id, 1);
END;

CREATE TRIGGER `sw_user_update` AFTER UPDATE ON `sw_user` FOR EACH ROW BEGIN
INSERT INTO sw_log(t_name, t_id, t_flag) values(sw_user, OLD.id, 2);
END;

CREATE TRIGGER `sw_user_delete` AFTER DELETE ON `sw_user` FOR EACH ROW BEGIN
INSERT INTO sw_log(t_name, t_id, t_flag) values(sw_user, OLD.id, 3);
END;

 

first, I insert some records:

INSERT INTO `sw_user`(name, mobile, sex, address) VALUES(coffee, 1801863971x, 1, Shenzhen);
INSERT INTO `sw_user`(name, mobile, sex, address) VALUES(sam, 1701892512y, 1, Beijing);
INSERT INTO `sw_user`(name, mobile, sex, address) VALUES(bruce, 1391766716x, 1, Nanjing);
INSERT INTO `sw_user`(name, mobile, sex, address) VALUES(vicky, 138982589x, 1, Shanghai);

 

sw_user

技术分享图片

sw_log

技术分享图片

second, I update and delete one record

UPDATE `sw_user` SET mobile = 1567892587x WHERE id = 1;
DELETE FROM `sw_user` WHERE id = 1;

技术分享图片

技术分享图片

 

How to Create Triggers in MySQL

标签:poi   after   inf   tiny   ESS   innodb   value   ima   sign   

原文地址:https://www.cnblogs.com/coffee_cn/p/9900062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!