MySQL 和自动增量一致性

标签 mysql auto-increment

我想在插入后立即获取表的自动增量 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/

相关文章:

mysql - 从 Mysql 中清除电子邮件地址

c# - 在Visual Studio中制作Entity Framework 6模型会关闭向导并断开MYSQL连接数据库的连接

MySQL选择性GROUP BY,使用最大值

mysql - 在 symfony2 和 mysql 中生成主键

sql - 其他用户能否闯入我的sql操作序列?

mongodb - 使用 loopback.js 和 MongoDB 自动递增

mysql - 奇怪的 MySQL 错误 #1242 - 子查询返回超过 1 行

php - sql语句从数据库中取出恰好5天前的数据

mysql - 使用 MySQL 中另一个表的数据填充表时,启动 auto_increment 值不起作用

database - phpMyAdmin中建表时的自增复选框选项在哪里?