[英]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. 我想从数据库表中获取最后插入的4个ID,基本上应该可以获取4个最新/最近添加的字段。
I know there is a lastInsertId()
function in PHP which gets the last one. 我知道PHP中有一个
lastInsertId()
函数可以获取最后一个。
For example if I have the last inserted ID stored to a variable like this: 例如,如果我将最后插入的ID存储到这样的变量中:
$productID = $db->lastInsertId();
But how do I get last 4 inserted ID's rather than just the last one? 但是,如何获得最后插入的4个ID,而不仅仅是最后一个?
Is there a quick way around this? 有没有解决的办法?
Assuming there is an ID and it is the primary key for each record. 假设有一个ID,它是每个记录的主键。
Edit 编辑
My ID fields are auto increment as I forgot to mention previously 我的ID字段是自动递增的,我之前已经提到过
select WHATEVER_FIELDS from TABLE order by IDFIELD desc limit 4
MYSQL: LAST_INSERT_ID FUNCTION MYSQL:LAST_INSERT_ID功能
I will just bring here some of the notes mentioned there 我将把这里提到的一些笔记带到这里
So in order to retrieve last 4 Inserted IDs you must check the id for EACH insert/update you are doing. 因此,为了检索最后的4个插入的ID,您必须检查正在执行的每个插入/更新的ID。
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 选择最后4行不是一种选择-考虑一下:*人A插入具有autoid 1的行*人B插入具有autoid 2的行*人A插入具有autoid 3,4的行*人B插入具有autoid 5的行*人A插入了行具有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
如果您是A人,并且在每次插入后检查最后插入的ID,您将得到:
1, 3, 4, 6
如果您是B人,您将得到2, 5
如果您是A人并使用该查询选择您将得到3,4,5,6
And one more - if your rows have not autoincremented ID, here is something im doing: 还有一个-如果您的行没有自动增加ID,这是我在做的事情:
There is only 1 last inserted ID and that is after every query which makes an insert. 最后插入的ID只有1个,即在每次查询后插入的ID。
lastInsertId()
therefore returns that ID and you call it after the insert has been made. 因此,
lastInsertId()
返回该ID,并在插入后调用它。
That means you have to call lastInsertId()
4 times, after every insert query and store its result in an array. 这意味着您必须在每个插入查询之后调用
lastInsertId()
4次,并将其结果存储在数组中。
EDIT : I understand that last 4 IDs can be queried with SELECT, but that is not what the OP is asking. 编辑 :我知道可以使用SELECT查询最后4个ID,但这不是OP的要求。 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.
如果OP想要DB中的最后4个ID,而不是插入的最后4个ID,则应该以完全不同的方式形成问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.