Easy mysql question regarding primary keys and an insert(关于主键和插入的简单mysql问题)
问题描述
在mysql中,当自动递增时,如何获取用于插入操作的主键.
In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing.
基本上,我希望在语句完成时返回新的自动增量值.
Basically, i want the new autoincremented value to be returned when the statement completes.
谢谢!
推荐答案
您的澄清评论说您有兴趣确保 LAST_INSERT_ID() 在发生另一个并发 INSERT 时不会给出错误结果.请放心,无论其他并发活动如何,使用 LAST_INSERT_ID() 都是安全的.LAST_INSERT_ID() 仅返回当前会话期间生成的最新 ID.
Your clarification comment says that you're interested in making sure that LAST_INSERT_ID() doesn't give the wrong result if another concurrent INSERT happens. Rest assured that it is safe to use LAST_INSERT_ID() regardless of other concurrent activity. LAST_INSERT_ID() returns only the most recent ID generated during the current session.
你可以自己试试:
- 打开两个shell窗口,运行mysql每个客户端并连接到数据库.
- Shell 1:插入到带有AUTO_INCREMENT 键.
- 外壳 1:SELECT LAST_INSERT_ID(),查看结果.
- Shell 2:插入到同一个表中.
- 外壳 2:SELECT LAST_INSERT_ID(),查看与 shell 1 不同的结果.
- 外壳 1:SELECT LAST_INSERT_ID()再次,看到前面的重复结果.
如果你仔细想想,这是唯一有意义的方法.所有支持自动递增密钥机制的数据库都必须以这种方式运行.如果结果取决于其他客户端可能同时插入的竞争条件,那么将没有可靠的方法来获取当前会话中最后插入的 ID 值.
If you think about it, this is the only way that makes sense. All databases that support auto-incrementing key mechanisms must act this way. If the result depends on a race condition with other clients possibly INSERTing concurrently, then there would be no dependable way to get the last inserted ID value in your current session.
这篇关于关于主键和插入的简单mysql问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于主键和插入的简单mysql问题
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
