我想在插入后立即获取表的自动增量 ID。 LAST_INSERT_ID() 应该可以工作,但是它是 100% 完整的证明吗?这意味着如果在存储过程中同时执行两个语句,它将使用该上下文中的最后一个 ID,还是来自所建立的其他连接?
INSERT INTO foo (auto,text)
VALUES(NULL,'text'); # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text'); # use ID in second table
最佳答案
MySQL手册是这么说的
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Important If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.
The value of LAST_INSERT_ID() will be consistent across all versions if all rows in the INSERT or UPDATE statement were successful.
The currently executing statement does not affect the value of LAST_INSERT_ID().
If the previous statement returned an error, the value of LAST_INSERT_ID() is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID() is left undefined. For manual ROLLBACK, the value of LAST_INSERT_ID() is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.
所以,是的,如果您使用单个插入查询而不是分组查询,这是最好的方法
关于MySQL 和自动增量一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10128022/