前言
最近一個同事問我,為什么last_insert_id()得到的結果與預期的不一樣呢,于是我就認真的去研究的一下這個參數,下面是關于last_insert_id()的詳細介紹,一起來學習學習吧。
首先,舉個例子
| wing@3306>show create table tt;+-------+-----------------------------------------------------------------------------------------------------------------------+| Table | Create Table |+-------+-----------------------------------------------------------------------------------------------------------------------+| tt | CREATE TABLE `tt` ( `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 |+-------+-----------------------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)# 沒有指定值的時候,last_insert_id()符合預期希望wing@3306>insert into tt values();Query OK, 1 row affected (0.00 sec)wing@3306>select last_insert_id();+------------------+| last_insert_id() |+------------------+| 1 |+------------------+1 row in set (0.00 sec)wing@3306>insert into tt values();Query OK, 1 row affected (0.00 sec)wing@3306>select last_insert_id();+------------------+| last_insert_id() |+------------------+| 2 |+------------------+1 row in set (0.00 sec)# what?不是應該是5么,為什么是第一個插入的值3?last_insert_id開始有一點不符合預期了。。wing@3306>insert into tt values(),(),();Query OK, 3 rows affected (0.01 sec)Records: 3 Duplicates: 0 Warnings: 0wing@3306>select last_insert_id();+------------------+| last_insert_id() |+------------------+| 3 |+------------------+1 row in set (0.00 sec)wing@3306>insert into tt values(),(),();Query OK, 3 rows affected (0.01 sec)Records: 3 Duplicates: 0 Warnings: 0wing@3306>select last_insert_id();+------------------+| last_insert_id() |+------------------+| 6 |+------------------+1 row in set (0.00 sec)# 納尼?按照預期不是10么?為什么還是之前的6?last_insert_id()我不懂你啊。。wing@3306>insert into tt values(10);Query OK, 1 row affected (0.01 sec)wing@3306>select last_insert_id();+------------------+| last_insert_id() |+------------------+| 6 |+------------------+1 row in set (0.00 sec) | 
其次,研究一下
查閱MySQL官方文檔,真的太重要了。。。
官方出處:http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
官方文檔原話:
With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.
翻譯:
沒有參數的last_insert_id()返回的是最近一次針對autoincrement列執行的            
新聞熱點
疑難解答