简体   繁体   中英

How to get last 4 inserted ID's in MySQL

I want to get the last 4 inserted ID's from a database table, which should basically get the 4 latest / most recently added fields.

I know there is a lastInsertId() function in PHP which gets the last one.

For example if I have the last inserted ID stored to a variable like this:

$productID = $db->lastInsertId(); 

But how do I get last 4 inserted ID's rather than just the last one?

Is there a quick way around this?

Assuming there is an ID and it is the primary key for each record.

Edit

My ID fields are auto increment as I forgot to mention previously

select WHATEVER_FIELDS from TABLE order by IDFIELD desc limit 4

MYSQL: LAST_INSERT_ID FUNCTION

I will just bring here some of the notes mentioned there

  • If the most recent INSERT or UPDATE statement set more than one AUTO_INCREMENT value, the LAST_INSERT_ID function returns only the first AUTO_INCREMENT value.
  • The LAST_INSERT_ID function returns the last AUTO_INCREMENT value on a client-by-client basis, so it will only return the last AUTO_INCREMENT value for your client. The value can not be affected by other clients.
  • Executing the LAST_INSERT_ID function does not affect the value that LAST_INSERT_ID returns.

So in order to retrieve last 4 Inserted IDs you must check the id for EACH insert/update you are doing.

Selecting last 4 rows is not an option - consider this: * person A inserts row with autoid 1 * person B inserts row with autoid 2 * person A inserts row with autoid 3,4 * person B inserts row with autoid 5 * person A inserts row with autoid 6

If you are person A and after each insert you check the last inserted id you will get: 1, 3, 4, 6 if you are person B you will get 2, 5 If you are person A and use that query for selecting you will get 3,4,5,6

And one more - if your rows have not autoincremented ID, here is something im doing:

  • add column with index (char 32)
  • on insert fill that column with some data (unique);
  • after inserting - SELECT row where column is that data
  • update row column to null (its not needed now)

There is only 1 last inserted ID and that is after every query which makes an insert. lastInsertId() therefore returns that ID and you call it after the insert has been made.

That means you have to call lastInsertId() 4 times, after every insert query and store its result in an array.

EDIT : I understand that last 4 IDs can be queried with SELECT, but that is not what the OP is asking. If OP wants the last 4 IDs in the DB, not the last 4 IDs inserted, the question should be formed in a completely different way.

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