bitsCN.com
last_insert_id
自动返回最后一个 INSERT 或 UPDATE 操作为 AUTO_INCREMENT 列设置的第一个发生的值. 参考这里
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只返回插入的第一条记录产生的值. 比如
Magic CMS网站管理系统(政企版)采用PHP+Mysql架构,再原CMS系统的基础上精简出适合企业政府客户使用版本,继承了原系统的快捷,高效,灵活,实用的特点,保留了核心功能,系统支持自定义模版(极易整合dede模板)、支持扩展插件,自定义模型等功能,保留了文章模型,视频模型,图集模型,产品模型,能够胜任企业多种建站需求。BUG修复:1.修改了程序安装时部分数据无法正常导入的错误2.修改了程
- mysql> INSERT INTO t VALUES (NULL, 'aaaa'), (NULL, 'bbbb'), (NULL, 'cccc');
- mysql> SELECT * FROM t;
- +----+------+
- | id | name |
- +----+------+
- | 1 | Bob |
- | 2 | aaaa |
- | 3 | bbbb |
- | 4 | cccc |
- +----+------+
- mysql> SELECT last_insert_id();
- +------------------+
- | last_insert_id() |
- +------------------+
- | 2 |
- +------------------+
ID 2 是在插入第一条记录aaaa 时产生的. [当插入多条数据时。返回的id见 上。]
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 而不用担心其它客户端的活动,而且不需要加锁。
bitsCN.com









