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

时间:2011-07-20 02:48:43

标签: mysql triggers mysql-error-1442

我已经在互联网上寻找了许多地方mysql error #1442的原因

  

无法在存储的函数/触发器中更新表'unlucky_table',因为   它已被调用此存储的语句使用   功能/触发

有人说这是mysql中的一个错误或它没有提供的功能。

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);

现在after update trigger上的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?

1 个答案:

答案 0 :(得分:4)

更新时无法引用表格。

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

来自MySQL Docs:

触发器可以访问自己的表中的旧数据和新数据。触发器也可以影响其他表,但不允许通过调用函数或触发器的语句修改已经使用(用于读取或写入)的表。 (在MySQL 5.0.10之前,触发器无法修改其他表。)