插入多行,LAST_INSERT_ID return 1

insert many rows, LAST_INSERT_ID return 1

有:

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() return 1 ? 例外: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。 "last" 部分指的是最近的插入 语句 ,而不是该插入中最近的 id 值。