简体   繁体   中英

Auto_increment column value required

Suppose i have table with column auto_increment and multiple inserts are going on concurrently:

INSERT INTO service_request.service_request_data(emp_id,sales_force_id,type_of_request,rfp_rfi,closure_deadline,mode_of_submission,submission_date,clarification_date,extention_date,region,item_status,participants_status,reviewer_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

And, i need auto increment id for my inserted data. How can i get that. May be after my insert many insert would have happenend.

Kindly, help me to find out this.

You can use MySQL's function LAST_INSERT_ID() for that. Here is the documentation.

That function works per session (in other words, per connection ). If multiple INSERT s from different sessions (connections) are going on concurrently, each session (connection) will be returned the value it has inserted last, independently from other sessions (connections).

But please read the documentation thoroughly as that function behaves surprisingly in parts. For example, if the same session inserts multiple rows at once , LAST_INSERT_ID() will return the ID of the first row which has been inserted. So you eventually have to combine it with ROW_COUNT() to actually get the ID which the very last row inserted has generated.

Furthermore, you'll have to take into account how LAST_INSERT_ID() works in transactions, triggers and events, and what it does in case of transaction rollbacks or commits.

ROW_COUNT() can also be a complex beast with surprising behavior. For example, look what it does when used after an INSERT ... ON DUPLICATE KEY UPDATE statement. It is all in the documentation which you probably need to read multiple times to fully understand it (I had to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM