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
+----+--------+------+