1

我正在运行这个触发器

DELIMITER //
CREATE TRIGGER lestrigger
    AFTER INSERT ON examinations
   FOR EACH ROW
  BEGIN
    DECLARE the_last_inserted_id INT;
    SELECT LAST_INSERT_ID() INTO the_last_inserted_id;

END //
DELIMITER ;

插入后,last_inserted_id变量保存last_insert_id前一个插入的,而不是当前的。

为了解决这个问题,我做到了SELECT LAST_INSERT_ID()+1 INTO the_last_inserted_id;,但这并不是真正的修复,因为我不知道为什么触发器不能正常工作。这里有一个类似的问题,但我不明白。我应该总是添加1到我的触发器就像我做的那样?

4

1 回答 1

5

No, don't add 1 to last_insert_id() in the trigger.

In a multi-user, multi-threaded environment, you have no guarantee (and no expectation) that this will get you the id value that was assigned to the row that was just inserted. (An INSERT statement can insert more than one row, and a value for ID can be supplied so that it is not auto-generated.)

If what you want is the value that was actually assigned to the id column of the row that was just inserted (whether that was auto-generated, or whether the INSERT statement inserted more than one row), the do this:

SET the_last_inserted_id = NEW.id;

That gets the actual value that was assigned to the row (in an AFTER UPDATE FOR EACH ROW trigger. In a BEFORE UPDATE ... FOR EACH ROW trigger, this value could actually be modified.)

The behavior you are observing isn't wrong; it's what we expect. The behavior of the LAST_INSERT_ID() function is well documented here:

http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id

于 2013-07-22T18:55:39.133 回答