最新消息: 新版网站上线了!!!

mysql 触发器(插入、更新、删除) 实例

DROP TABLE IF EXISTS aaa;
CREATE TABLE `aaa` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
);
----------------------------------------------------------
DROP TABLE IF EXISTS bbb;
CREATE TABLE `bbb` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
);
 
INSERT INTO aaa(name) values('小王');
-----------------------------------------------------
DROP TRIGGER IF EXISTS t_afterinsert_on_aaa;
CREATE TRIGGER t_afterinsert_on_aaa
AFTER INSERT ON aaa
FOR EACH ROW
BEGIN
     insert into bbb(id,name) values(new.id,new.name);
END;
-------------------------------------------------------------
DELIMITER $$
DROP TRIGGER IF EXISTS `update_aaa` $$
CREATE
    TRIGGER `update_aaa` AFTER UPDATE
    ON `aaa`
    FOR EACH ROW BEGIN
UPDATE bbb SET name = new.name WHERE id = (SELECT id FROM aaa WHERE  name = new.name);
    END$$
  
-------------------------------------------
update aaa set name = '***' where id = 1;
-----------------------------------------------------------------------------
delimiter ||
DROP TRIGGER IF EXISTS t_afterdelete_on_aaa||
CREATE TRIGGER t_afterdelete_on_aaa
AFTER DELETE ON aaa
FOR EACH ROW
BEGIN
delete from bbb where id=old.id;
END||
.....

转载请注明:谷谷点程序 » mysql 触发器(插入、更新、删除) 实例