有关主键和插入的简单mysql问题 [英] Easy mysql question regarding primary keys and an insert

查看:90
本文介绍了有关主键和插入的简单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.

谢谢!

推荐答案

您的澄清评论说,您有兴趣确保在发生另一个并发INSERT时LAST_INSERT_ID()不会给出错误的结果.请放心,无论其他并行活动如何,使用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.

您可以自己尝试:

  1. 打开两个shell窗口,运行mysql 每个客户端并连接到 数据库.
  2. Shell 1:使用以下命令插入到表中: AUTO_INCREMENT键.
  3. Shell 1:SELECT LAST_INSERT_ID(), 查看结果.
  4. Shell 2:将INSERT插入同一表中.
  5. Shell 2:SELECT LAST_INSERT_ID(), 看到与shell 1不同的结果.
  6. Shell 1:SELECT LAST_INSERT_ID() 再次,看到前面的重复 结果.
  1. Open two shell windows, run mysql client in each and connect to database.
  2. Shell 1: INSERT into a table with an AUTO_INCREMENT key.
  3. Shell 1: SELECT LAST_INSERT_ID(), see result.
  4. Shell 2: INSERT into the same table.
  5. Shell 2: SELECT LAST_INSERT_ID(), see result different from shell 1.
  6. Shell 1: SELECT LAST_INSERT_ID() again, see a repeat of earlier result.

如果您考虑一下,这是唯一有意义的方法.所有支持自动递增密钥机制的数据库都必须采用这种方式.如果结果取决于与其他客户端可能同时插入的竞争条件,那么将没有可靠的方法来获取当前会话中最后插入的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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆