今天给MySQL数据库的表创建触发器,想达到的效果是:修改a表的字段received之后,同时要将b表中的registerStatus更新为1,将registerIP改为receive值。
1、首先写建立触发器的sql语句:
1)插入时的:
CREATE TRIGGER insertref BEFORE INSERT ON a
FOR EACH ROW BEGIN
UPDATE b SET registerStatus =1 WHERE NEW.id = id and NEW.received is not null and NEW.received !='';
update b set registerIP=NEW.received where NEW.id = id;
end
2)删除时:
CREATE TRIGGER deleteref BEFORE DELETE ON a
FOR EACH ROW begin
update b set registerStatus =0 WHERE OLD.id = id;
update b set registerIP=NULL where OLD.id = id;
end
3)更新时:
CREATE TRIGGER updateref BEFORE UPDATE ON a
FOR EACH ROW BEGIN
update b set registerIP=NEW.received where OLD.id=id;
end
问题1:
写完语句执行的时候,报错,执行不了,原因是用phpMyAdmin执行建立触发器的时候,要将
输入sql语句页面的下方的Delimiter中输入//。
问题2:在建立好触发器之后,在做测试的时候,在a表中无法插入数据,报错:
1558 - Column count of mysql.proc is wrong. Expected 20, found 16. Created with MySQL 50018, now running 50146. Please use mysql_upgrade to fix this error.
网上有很多帖子说是因为,之前升级过数据库,但是数据结构没有升级造成的。
解决办法:执行 sudo mysql_upgrade -u root -p 提示输入密码,输入密码之后,重启数据库。则可以插入数据了。