Maison > base de données > tutoriel mysql > le corps du texte

mysql触发器实例_MySQL

WBOY
Libérer: 2016-06-01 13:17:27
original
1099 Les gens l'ont consulté

测试表1

DROP TABLE IF EXISTS test;                  CREATE TABLE test (    id           bigint(11) unsigned NOT NULL AUTO_INCREMENT,    name         varchar(100) NOT NULL DEFAULT '',    type         varchar(100),  create_time  datetime,    PRIMARY KEY (ID)  ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;  
Copier après la connexion

测试表2

DROP TABLE IF EXISTS test_hisy;                  CREATE TABLE test_hisy (    id           bigint(11) unsigned NOT NULL AUTO_INCREMENT,    name         varchar(100) NOT NULL DEFAULT '',    type         varchar(100),  create_time  datetime,  operation    varchar(100) COMMENT '操作类型',  PRIMARY KEY (ID)  ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;  
Copier après la connexion

insert触发器

表test新增记录后,将type值为“1”的记录同时插入到test_hisy表中(AFTER INSERT:录入后触发, BEFORE INSERT:录入前触发)

DELIMITER //DROP TRIGGER IF EXISTS t_after_insert_test//CREATE TRIGGER t_after_insert_testAFTER INSERT ON testFOR EACH ROWBEGIN    IF new.type='1' THEN    insert into test_hisy(name, type, create_time, operation)     values(new.name, new.type, new.create_time, 'insert');    END IF;END;//
Copier après la connexion

update触发器

表test修改时,若type值为“2”则将修改前的记录同时插入到test_hisy表中(AFTER UPDATE:修改后触发, BEFORE UPDATE:修改前触发)

DELIMITER //DROP TRIGGER IF EXISTS t_before_update_test//CREATE TRIGGER t_before_update_testBEFORE UPDATE ON testFOR EACH ROWBEGIN    IF new.type='2' THEN    insert into test_hisy(name, type, create_time, operation)     values(old.name, old.type, old.create_time, 'update');    END IF;END;//
Copier après la connexion

delete触发器

表test删除记录前,将删除的记录录入到表test_hisy中(AFTER DELETE:删除后触发, BEFORE DELETE:删除前触发)

DELIMITER //DROP TRIGGER IF EXISTS t_before_delete_test//CREATE TRIGGER t_before_delete_testBEFORE DELETE ON testFOR EACH ROWBEGIN    insert into test_hisy(name, type, create_time, operation)     values(old.name, old.type, old.create_time, 'delete');END;//
Copier après la connexion
注:以上触发器例子中出现的new为修改后的数据, old为修改前的数据
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!