Today, with people to discuss the PHP high concurrency under the last_insert_id of the correctness of the first people are more vague, and then through the common query information, the problem has a relatively clear understanding, special hair This article, to commemorate.
First look at the official version of LAST_INSERT_ID () in MySQL: last_insert_id () automatically returns the value of the first table set for the Auto_increment column in the last INSERT or update query. MySQL last_insert_id Note: First, query and insert the connection object used must be the same, otherwise the return value is not predictable. Second, last_insert_id is not table-Independent, if you insert data into table A and then insert data into table B, LAST_INSERT_ID returns the ID value of table B. www.2cto.com Third, if you use an INSERT statement to insert multiple rows, last_insert_id () returns only the value produced when the first row of data is inserted. If you use Insert ignore and the record is ignored, the auto_increment counter does not increment, and last_insert_id () returns 0, which reflects that no records were inserted. According to these four principles, we are talking about high concurrent site access when the insertion is taken from the growth value is actually mainly related to the first rule and the second rule. That is, to ensure the correctness of the last_insert_id, the same connection must be the same, and last_insert_id to be executed immediately in INSERT. So if the database cache pool is common connection may be problematic, multithreaded operations can also be problematic after the insert is executed by another insert. The PHP database connection itself is page-level, so that the buffer pool will not appear, and then the PHP page execution itself is a single-threaded, so that the order of the last_insert_id must be written immediately after the INSERT execution, There will be no other insert execution in the middle. Www.2cto.com in summary, PHP page-level, single-threaded actually has ensured that the MySQL last_insert_id natural is correct, with high concurrency does not matter. That is, PHP, MySQL last_insert_id is always correct, casually use, no problem. Author Zhaokaijin
LAST_INSERT_ID () analysis in MySQL