有:
1. create DB
2. create Table
3. insert 3 rows
4. select LAST_INSERT_ID()
这里的测试代码:
DROP DATABASE IF EXISTS TEST;
CREATE DATABASE TEST;
USE TEST;
CREATE TABLE test (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
age INT
);
INSERT INTO test (age) VALUES (1), (2), (3);
SELECT LAST_INSERT_ID();
为什么 LAST_INSERT_ID() 返回 1 ? 异常(exception):3
如何获取有效的 LAST_INSERT_ID() ?
最佳答案
MySQL documentation清楚地解释了这种行为:
With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first (emphasis mine) automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.
插入中自动递增序列生成的第一个值是 1,而不是 2 或 3,因此返回值 1。
我认为您的困惑在于名称LAST_INSERT_ID
。 “最后”部分指的是最近的插入语句,而不是该插入中最新的id
值。
关于mysql - 插入多行,LAST_INSERT_ID 返回 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57620278/