Query-getting last inserted row id in mysql using

2019-09-22 07:08发布

I want to get last inserted row id in mysql any one help me Table field is

enter image description here

标签: mysql
2条回答
一夜七次
2楼-- · 2019-09-22 07:47

If you want to get the id just after the insertion, use LAST_INSERT_ID():

SELECT LAST_INSERT_ID();

This will return the AUTO_INCREMENT value of the last inserted element (in your current connection).

If you want to know which is the last inserted value in a determined table, use any of the queries provided in the other answers.

查看更多
男人必须洒脱
3楼-- · 2019-09-22 07:57

You can use LAST_INSERT_ID(), but you should be aware that (you not only should have the AUTO_INCREMENENT), but it does operates in at connection level. This is, it will return the last_insert_id() for the current connection and not the last_insert_id() that another connection --that might be happening meanwhile-- generated.

Example (lets say the operations arrive the database in the following order):

-Connection A : user A -> insert order (id = 1000), lets say $20
-Connection B : user B -> insert order (id = 1001), lets say $50
.... multiple orders from other users are placed
-Connection B : you retrieve last_insert_id (value 1001) and you retrieve the order amount, and update the user B profile with the total revenue generated (+$50).
-Connection A : you retrieve last_insert_id (value 1000) and you retrieve the order amount, and update the user A profile with the total revenue generated (+$20).

You should be aware that last-insert_id() operates on a connection level, therefore you want to keep the connection open until you are finished. You should not use things like do a max on the database, because on a web environment you don't have control on how many users will use your app at same time, and in which order the operations will be executed and most important you want to keep your database consistent.

查看更多
登录 后发表回答