mysql - mysql错误1442的真正原因是什么?

标签 mysql triggers mysql-error-1442

嗯,我在互联网上查找了很多地方来查找 mysql 错误 #1442 的原因,上面写着

Can't update table 'unlucky_table' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

有人说这是 mysql 中的一个 bug 或者它不提供的功能。

MySQL triggers can't manipulate the table they are assigned to. All other major DBMS support this feature so hopefully MySQL will add this support soon.

有人声称这是由于递归行为造成的 when you insert a record mysql is doing some lock stuff. you can't insert/update/delete rows of the same table where you insert.. because then the trigger would called again and again.. ending up in a recursion

During the insert/update you have access to the NEW object which contains all of the fields in the table involved. If you do a before insert/update and edit the field(s) that you want to change in the new object it will become a part of the calling statement and not be executed as a separately (eliminating the recursion)

现在我不明白为什么这是递归的。我有一个案例,其中我有 2 个表 table1table2 并且我运行 sql 查询为

update table1 set avail = 0 where id in (select id from table2 where duration < now() - interval 2 hour);

现在我在table1上有一个更新后触发器作为

CREATE TRIGGER trig_table1 AFTER UPDATE ON table1
FOR EACH ROW begin
if old.avail=1 and new.avail=0 then
delete from table2 where id=new.id;
end if;

现在,当我执行更新查询时,我收到 1442 错误。 在这种情况下什么是递归?

is this error a lack of feature in mysql?
OR
does this have to do with how mysql executes queries?
OR
is there something logically wrong with executing such queries?

最佳答案

更新表时无法引用表。

/* my sql does not support this */
UPDATE tableName WHERE 1 = (SELECT 1 FROM tableName)

来自MySQL Docs:

A trigger can access both old and new data in its own table. A trigger can also affect other tables, but it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger. (Before MySQL 5.0.10, a trigger cannot modify other tables.)

关于mysql - mysql错误1442的真正原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490921/

相关文章:

mysql - 从 2 个表中获取记录数 - 一对多关系

MySQL REGEXP 选择数字

MySQL触发器删除传递的用户ID

oracle - ORACLE回滚和触发

mysql - 错误代码 : 1442. 无法更新存储函数/触发器中的表 'students'

android - 发布 Android 应用程序的服务器要求

python - 如何在 sqlalchemy ORM 查询中使用 NOT IN 子句

代码末尾的 MySQLTrigger 语法错误

mysql trigger 存储触发器已被调用存储触发器的语句使用