获取插入行的字段值 [英] Get field value of inserted row
问题描述
我想编写一个函数,它为插入的行返回一列的值(本例中是一个自动递增的主键)。
基本上,我想插入一些新的数据,生成一个新的主键,然后获得该键。我可以简单地在表中查找最高主键,但也有可能其他人也可以运行该功能,并且我可以返回错误的键,对吗?
如何协商这个问题最简单的方法是什么?
正如评论所指出的,来自 MySQL文档:
mysql> SELECT LAST_INSERT_ID();
- > 195
这个 LAST_INSERT_ID()
函数不是受到像 SELECT MAX(id)
这样的竞争条件的影响,因为它在MySQL中专用于您的连接。它返回为您的最后一次插入生成的ID,而不是任何人的最后一次插入。
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?
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.
这篇关于获取插入行的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!