触发器
CREATE TRIGGER trigger_name trigger_time trigger_event ON tb_name FOR EACH ROW trigger_stmt
trigger_name:触发器的名称
tirgger_time:触发时机,为BEFORE或者AFTER
trigger_event:触发事件,为INSERT、DELETE或者UPDATE
tb_name:表示建立触发器的表明,就是在哪张表上建立触发器
trigger_stmt:触发器的程序体,可以是一条SQL语句或者是用BEGIN和END包含的多条语句
所以可以说MySQL创建以下六种触发器:
BEFORE INSERT,BEFORE DELETE,BEFORE UPDATE
AFTER INSERT,AFTER DELETE,AFTER UPDATE
一般情况下,mysql默认是以 ; 作为结束执行语句,与触发器中需要的分行起冲突
为解决此问题可用DELIMITER,如:DELIMITER ||,可以将结束符号变成||
当触发器创建完成后,可以用DELIMITER ;来将结束符号变成;
drop trigger user_log;#删除触发器
drop TRIGGER IF EXISTS userlog_add;
DELIMITER $
CREATE TRIGGER userlog_add AFTER INSERT ON `user` FOR EACH ROW
BEGIN
INSERT INTO user_logs (USER,TIME,logs)VALUES(CURRENT_USER(),CURRENT_TIMESTAMP(),'INSERT' );
END $
DELIMITER ;
drop TRIGGER IF EXISTS userlog_del;
DELIMITER $
CREATE TRIGGER userlog_del BEFORE DELETE ON `user` FOR EACH ROW
BEGIN
INSERT INTO user_logs (USER,TIME,logs)VALUES(CURRENT_USER(),CURRENT_TIMESTAMP(),'DELETE' );
END $
DELIMITER ;
drop TRIGGER IF EXISTS userlog_update;
DELIMITER $
CREATE TRIGGER userlog_update AFTER UPDATE ON `user` FOR EACH ROW
BEGIN
INSERT INTO user_logs (USER,TIME,logs)VALUES(CURRENT_USER(),CURRENT_TIMESTAMP(),'UPDATE' );
END $
DELIMITER ;
select * from information_schema.`PROCESSLIST` where `USER`=substring_index(CURRENT_USER(),'@',1) and info is not null #MySQL查询正在执行的SQL语句