使用MySQL的LAST_INSERT_ID


自动返回最后一个 INSERT 或 UPDATE 操作为 AUTO_INCREMENT 列设置的第一个发生的值. 参考这里

(经测试,last_insert_id()的值与update操作无关。(笔者注))

如:mysql> select * from a;
+-------+----+
| value | id |
+-------+----+
| test1 | 1 |
| test2 | 2 |
+-------+----+

mysql>   update a set id=3 where id=1;

mysql> select * from a;
+-------+----+
| value | id |
+-------+----+
| test2 | 2 |
| test1 | 3 |
+-------+----+

mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                2 |
+------------------+

注意最终的id号是2而不是3.

(以上代码由笔者添加。)

The ID that was generated is maintained in the server on a per-connection basis.

LAST_INSERT_ID是基于单个connection的, 不可能被其它的客户端连接改变。

可以用 SELECT LAST_INSERT_ID(); 查询LAST_INSERT_ID的值.

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

使用单INSERT语句插入多条记录, LAST_INSERT_ID只返回插入的第一条记录产生的值. 比如

  1. mysql> INSERT INTO t VALUES (NULL, 'aaaa'), (NULL, 'bbbb'), (NULL, 'cccc');   
  2. mysql> SELECT * FROM t;   
  3. +----+------+   
  4. | id | name |   
  5. +----+------+   
  6. |   1 | Bob   |   
  7. |   2 | aaaa |   
  8. |   3 | bbbb |   
  9. |   4 | cccc |   
  10. +----+------+   
  11. mysql> SELECT LAST_INSERT_ID();   
  12. +------------------+   
  13. | LAST_INSERT_ID() |   
  14. +------------------+   
  15. |                 2 |   
  16. +------------------+  

ID 2 是在插入第一条记录aaaa 时产生的.

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

一般情况下获取刚插入的数据的id,使用select max(id) from table 是可以的。

但在多线程情况下,就不行了。在多用户交替插入数据的情况下max(id)显然不能用。

这就该使用LAST_INSERT_ID了,因为LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的Connection对象,LAST_INSERT_ID函数将返回该Connection对AUTO_INCREMENT列最新的insert or update操作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。

相关内容