SELECT LAST_INSERT_ID() [英] SELECT LAST_INSERT_ID()
本文介绍了SELECT LAST_INSERT_ID()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释MySQL函数LAST_INSERT_ID()的工作原理。我正在尝试获取数据库中最后插入行的ID,但每次都得到1.
Can somebody explain how works MySQL function LAST_INSERT_ID(). I'm trying to get id of last inserted row in database, but every time get 1.
我使用mybatis。
I use mybatis.
示例查询是:
<insert id="insertInto" parameterType="Something" timeout="0">
INSERT INTO something (something) VALUES (#{something})
<selectKey resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
代码:
System.out.println("Id : " + id)
输出:
Id : 1
推荐答案
LAST_INSERT_ID
返回隐式插入的最后一个值当前会话中的AUTO_INCREMENT
列。
CREATE TABLE mytable (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, value INT NOT NULL);
要使列自动增量,您应该从 INSERT中省略它
list:
To make the column autoincrement, you should omit it from the INSERT
list:
INSERT
INTO mytable (value)
VALUES (1)
或提供 NULL
值:
INSERT
INTO mytable (id, value)
VALUES (NULL, 1)
之后,
SELECT LAST_INSERT_ID()
将返回值 AUTO_INCREMENT
已插入 id
列。
如果符合以下条件,则无效:
This will not work if:
- 您为
AUTO_INCREMENT
列提供显式值 - 您
- 在同一语句中插入多行(
LAST_INSERT_ID()
将返回插入的第一行的值,而不是最后一行的值。
- You provide the explicit value for the
AUTO_INCREMENT
column - You call
LAST_INSERT_ID
in another session - You insert more than one row in the same statement (
LAST_INSERT_ID()
will return the value of the first row inserted, not the last one).
这篇关于SELECT LAST_INSERT_ID()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文