Easy mysql question regarding primary keys and an insert

一笑奈何 提交于 2019-11-27 22:26:26

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.

You can try it yourself:

  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.

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.

The MySQL Docs describe the function: LAST_INSERT_ID()

[select max(primary_key_column_name) from table_name] Ahhh not nessecarily. I am not an MySQL guy but there are specific way to get the last inserted id for the last completed action that are a little more robust than this. What if an insert has happened between you writing to the table and querying it? I know about because it stung me many moons ago (so yeah it does happen). If all else fails read the manual: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!