首頁  >  文章  >  資料庫  >  LAST_INSERT_ID() 在 MySQL 的多行 INSERT 語句中表現如何?

LAST_INSERT_ID() 在 MySQL 的多行 INSERT 語句中表現如何?

Linda Hamilton
Linda Hamilton原創
2024-11-14 20:14:02728瀏覽

How Does LAST_INSERT_ID() Behave in Multi-Row INSERT Statements in MySQL?

Returning the Last Insert ID in Multi-Row INSERT Statements Using LAST_INSERT_ID() in MySQL

When executing multiple record insertions in MySQL, understanding the behavior of the LAST_INSERT_ID() function becomes crucial. Unlike single-row insertions where it provides the ID of the inserted row, LAST_INSERT_ID() behaves differently with multi-row INSERT statements.

For example, consider the following query:

INSERT INTO people (name, age)
VALUES ('William', 25), ('Bart', 15), ('Mary', 12);

After executing this statement, one might expect the LAST_INSERT_ID() function to return the ID of the last inserted row (3). However, the behavior of LAST_INSERT_ID() diverges from this expectation.

LAST_INSERT_ID() Returns the First Insert ID

In the context of multiple record INSERT statements, LAST_INSERT_ID() returns the ID generated for the first inserted row only. This behavior is explicitly documented in MySQL's documentation:

Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

This design decision ensures that the same INSERT statement can be easily reproduced on another server without any issues. By using the ID of the first inserted row, reproducing the intended behavior becomes straightforward.

Implications for Code Design

Understanding this behavior is crucial when designing code that relies on the LAST_INSERT_ID() function for multi-row insertions. Developers should avoid relying on LAST_INSERT_ID() to determine the specific IDs of inserted rows in such scenarios. Alternative approaches for tracking or accessing row IDs in multi-row insertions should be considered.

以上是LAST_INSERT_ID() 在 MySQL 的多行 INSERT 語句中表現如何?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn