SELECT LAST_INSERT_ID() as id FROM table1
Why does this query sometimes return the last inserted id of another table other than table1?
I call it in Node.js (db-mysql plugin) and I can only do queries.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
LAST_INSERT_ID()can only tell you theIDof the most recently auto-generatedIDfor that entire database connection, not for each individual table, which is also why the query should only readSELECT LAST_INSERT_ID()– without specifying a table.As soon as you fire off another
INSERTquery on that connection, it gets overwritten. If you want the generatedIDwhen you insert to some table, you must runSELECT LAST_INSERT_ID()immediately after doing that (or use some API function which does this for you).If you want the newest
IDcurrently in an arbitrary table, you have to do aSELECT MAX(id)on that table, whereidis the name of yourIDcolumn. However, this is not necessarily the most recently generatedID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform anINSERTbetween your ownINSERTand your selection of theID.(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in
table1.)