last_insert_id
Automatically returns the first occurrence of the last INSERT or UPDATE action set for the Auto_increment column. Refer here
The ID is generated are maintained in the server on a per-connection basis.
LAST_INSERT_ID is based on a single connection and cannot be changed by other client connections.
You can use SELECT last_insert_id (); The value of the query 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 .
Using a single INSERT statement to insert multiple records, LAST_INSERT_ID only returns the value produced by the first record inserted. Like what
- 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 is generated when the first record aaaa is inserted.
LAST_INSERT_ID is not related to table, last_insert_id will change if data is inserted into table A, and then the data is injected into form B.
In general, it is possible to get the ID of the data just inserted, using SELECT Max (ID) from table.
But in the case of multithreading, it is not. Max (ID) is obviously not available in the case where multiple users are alternately inserting data.
This should use last_insert_id, because last_insert_id is connection based, as long as each thread uses a separate connection object, Last_insert_ The ID function returns the ID of the first record generated by the connection for the latest insert or update operation on the Auto_increment column. This value cannot be affected by other clients (Connection), which guarantees that you will be able to retrieve your ID without worrying about other clients ' activities and do not need to lock.
Original: http://wangcheng.iteye.com/blog/54293
Use MySQL's last_insert_id--to turn