mysql数据库多线程LAST_INSERT_ID()

msql多线程的时候用LAST_INSERT_ID()比max(id)高效且不会被其他线程(connection)打断。

INSERT INTO wp_posts (post_title,post_content,post_author,post_name,post_date,post_excerpt,to_ping,pinged,post_content_filtered) VALUES ('[标签:标题]','[标签:内容]','1','[标签:slug]','[系统时间转化:yyyy-MM-dd HH:mm:ss]','','','','')
INSERT INTO wp_term_relationships (object_id,term_taxonomy_id) VALUES (LAST_INSERT_ID(),1)

但是LAST_INSERT_ID函数有几点必须注意,直接复制过来的:

  • If the most recent INSERT or UPDATE statement set more than one AUTO_INCREMENT value, the LAST_INSERT_ID function returns only the first AUTO_INCREMENT value.
  • The LAST_INSERT_ID function returns the last AUTO_INCREMENT value on a client-by-client basis, so it will only return the last AUTO_INCREMENT value for your client. The value can not be affected by other clients.
  • Executing the LAST_INSERT_ID function does not affect the value that LAST_INSERT_ID returns.

个人总结的几个注意事项:

1、如果一次insert插入多条value值,LAST_INSERT_ID()获取的是第一条value记录的自增ID;

2、如果是多条insert,插入同一个table表,LAST_INSERT_ID()获取的是最后一条insert记录的自增ID;

3、如果insert的表发生了变化,LAST_INSERT_ID()获取的自增ID也会变化,它返回的是最后一条insert记录的自增ID。

参考链接:

https://www.techonthenet.com/mysql/functions/last_insert_id.php

https://stackoverflow.com/questions/3837990/last-insert-id-mysql

https://docs.singlestore.com/managed-service/en/reference/sql-reference/information-functions/last_insert_id.html

本文链接: https://www.168itw.com/tech/mysql_last_insert_id/
转载请注明转载自:168itw

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注