假设我在我的一张表中执行 MySQL INSERT
并且该表的列 item_id
设置为 autoincrement
和主键
.
如何让查询在同一个查询中输出新生成的主键item_id
的值?
目前我正在运行第二个查询来检索 id,但这似乎不是一个好的做法,因为这可能会产生错误的结果...
如果这不可能,那么确保我检索到正确 id 的最佳做法是什么?
最佳答案
您需要使用 LAST_INSERT_ID()
函数:http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
例如:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();
这将使您返回 您 插入的最后一行的 PRIMARY KEY
值:
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.
所以 LAST_INSERT_ID()
返回的值是每个用户的,并且不受可能在服务器上运行的其他查询的影响来自其他用户.
关于mysql - 从 MySQL 插入查询中获取新记录的主键 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17112852/