我有下表[页面]:
pgid|pgname|pgorder
----+------+-------
1 |Page#1| 1
2 |Page#2| 2
3 |Page#3| 3
4 |Page#4| 4
列“ pgorder”代表特定页面的位置.
我需要触发器,该触发器将在删除一页记录后自动将其余页面的位置转移(减少)一个位置.
所以当我删除例如pgid = 2该表应如下所示:
pgid|pgname|pgorder
----+------+-------
1 |Page#1| 1
3 |Page#3| 2
4 |Page#4| 3
这个MySQL触发器应该是什么样的?
解决方法:
您不能使用DML语句来修改为其触发触发器的表.您收到此错误:
ERROR 1442 (HY000): Can't update table 'pages' in stored function/trigger because
it is already used by statement which invoked this stored function/trigger.
原因是它冒着无限循环或至少死锁的风险.如果DELETE在触发触发器之前锁定了表,然后在触发器内部执行了UPDATE,要求对表进行锁定,则两者均无法进行.
查看https://dev.mysql.com/doc/refman/5.6/en/stored-program-restrictions.html:
A stored function or trigger cannot modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
正确的解决方案是分两步执行此任务:首先是DELETE,然后是UPDATE:
DELETE FROM pages WHERE pgorder = 3;
UPDATE pages SET pgorder = pgorder-1 WHERE pgorder > 3;
您可以在事务内执行这两个DML语句,以确保它们在提交之前都成功,否则回滚该事务.