Get field value of inserted row

大城市里の小女人 提交于 2019-12-02 09:21:28

问题


I want to write a function that returns the value of a column (in this case, an auto-incrementing primary key) for a row that it inserts.

Essentially, I want to insert some new data, have a new primary key generated, then get that key. I could simply look for the highest primary key in the table, but it is possible that someone else could be running the function as well, and I could return the wrong key, right?

What's the simplest way to negotiate this problem?


回答1:


As pointed in the comments, from MySQL documentation:

mysql> SELECT LAST_INSERT_ID();
    -> 195

This LAST_INSERT_ID() function is not subject to a race condition like SELECT MAX(id) might be, because it's maintained within MySQL specific to your connection. It returns the ID generated for your last insert, not anybody's last insert.



来源:https://stackoverflow.com/questions/27676672/get-field-value-of-inserted-row

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