INSERT with AUTO INCREMENT LAST INSERT ID()

当一个表有 AUTO_INCREMENT PRIMARY KEY 时,通常一个表没有插入该列。相反,请指定所有其他列,然后询问新 ID 是什么。

CREATE TABLE t (
    id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL,
    this ...,
    that ...,
    PRIMARY KEY(id) );

INSERT INTO t (this, that) VALUES (..., ...);
SELECT LAST_INSERT_ID() INTO @id;
INSERT INTO another_table (..., t_id, ...) VALUES (..., @id, ...);

请注意,LAST_INSERT_ID() 与会话绑定,因此即使多个连接插入到同一个表中,每个连接都会获得自己的 id。

你的客户端 API 可能有另一种方法来获取 LAST_INSERT_ID() 而不实际执行 SELECT 并将值交回客户端而不是将其留在 MySQL 内的 @variable 中。这通常是优选的。

更长,更详细的例子

IODKU 的正常用法是根据某些 UNIQUE 键触发重复键,而不是 AUTO_INCREMENT PRIMARY KEY。以下说明了这一点。请注意,它并没有在 INSERT 供应 id

设置示例如下:

CREATE TABLE iodku (
    id INT AUTO_INCREMENT NOT NULL,
    name VARCHAR(99) NOT NULL,
    misc INT NOT NULL,
    PRIMARY KEY(id),
    UNIQUE(name)
) ENGINE=InnoDB;

INSERT INTO iodku (name, misc)
    VALUES
    ('Leslie', 123),
    ('Sally', 456);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0
+----+--------+------+
| `id` | name   | misc |
+----+--------+------+
|  1 | Leslie |  123 |
|  2 | Sally  |  456 |
+----+--------+------+

IODKU 执行更新的情况和 LAST_INSERT_ID() 检索相关的 id

INSERT INTO iodku (name, misc)
    VALUES
    ('Sally', 3333)            -- should update
    ON DUPLICATE KEY UPDATE    -- `name` will trigger "duplicate key"
    id = LAST_INSERT_ID(id),
    misc = VALUES(misc);
SELECT LAST_INSERT_ID();       -- picking up existing value
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                2 |
+------------------+

IODKU 执行插入LAST_INSERT_ID() 检索新 id 的情况:

INSERT INTO iodku (name, misc)
    VALUES
    ('Dana', 789)          -- Should insert
    ON DUPLICATE KEY UPDATE
    id = LAST_INSERT_ID(id),
    misc = VALUES(misc);
SELECT LAST_INSERT_ID();   -- picking up new value
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                3 |
+------------------+

结果表内容:

SELECT * FROM iodku;
+----+--------+------+
| `id` | name   | misc |
+----+--------+------+
|  1 | Leslie |  123 |
|  2 | Sally  | 3333 |  -- IODKU changed this
|  3 | Dana   |  789 |  -- IODKU added this
+----+--------+------+