文章来自: http://www.cnblogs.com/JohnABC/p/3727068.html
第一、查询和插入所使用的Connection对象必须是同一个才可以,否则返回值是不可预料的。
使 用这函数向一个给定Connection对象返回的值是该Connection对象产生对影响AUTO_INCREMENT列的最新语句第一个 AUTO_INCREMENT值的。这个值不能被其它Connection对象的影响,即它们产生它们自己的AUTO_INCREMENT值。
第二、LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID返回表b中的Id值。
第三、 假如你使用一条INSERT语句插入多个行, LAST_INSERT_ID() 只返回插入的第一行数据时产生的值。其原因是这使依靠其它服务器复制同样的 INSERT语句变得简单。
下面做个简单测试:
session 1:
"root@localhost Thu Nov 3 03:18:51 2016 03:18:51 [test]>CREATE TABLE t (
-> id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
-> name VARCHAR(10) NOT NULL
-> );
Query OK, 0 rows affected (0.09 sec)
"root@localhost Thu Nov 3 03:18:53 2016 03:18:53 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 0 |
+------------------+
1 row in set (0.00 sec)
"root@localhost Thu Nov 3 03:19:14 2016 03:19:14 [test]>INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.00 sec)
"root@localhost Thu Nov 3 03:19:30 2016 03:19:30 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)
"root@localhost Thu Nov 3 03:19:35 2016 03:19:35 [test]>select max(id) from t;
+---------+
| max(id) |
+---------+
| 1 |
+---------+
1 row in set (0.00 sec)
session 2:
在session2 中向表中再插入一行,查看 last_insert_id () 的值为 2.
"root@localhost Thu Nov 3 03:19:54 2016 03:19:54 [test]>INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.01 sec)
"root@localhost Thu Nov 3 03:20:03 2016 03:20:03 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 2 |
+------------------+
1 row in set (0.00 sec)
session 1:
再回到session 1 ,查看 last_insert_id () 的值还是 1 。
"root@localhost Thu Nov 3 03:19:39 2016 03:19:39 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)