[英]Get last record id from set of records in mysql query without fetching all records
I have a query that fetches a set of records as shown:我有一个获取一组记录的查询,如下所示:
select id
from wallactions
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY)
order by id desc LIMIT $priorRecordsCnt
The LIMIT variable $priorRecordsCnt
changes often and can grow very large. LIMIT 变量
$priorRecordsCnt
经常变化并且可以变得非常大。 It's necessary because i need to know the last id in that set of records based on the $priorRecordsCnt
count value.这是必要的,因为我需要根据
$priorRecordsCnt
计数值知道该组记录中的最后一个 id。
The problem is, I need to only access the last id in this set, as shown:问题是,我只需要访问这个集合中的最后一个 id,如图:
$last=array_values(array_slice($result,-1))[0]['id'];
I feel like this is pretty expensive to just get the id of the last record in the set.我觉得仅获取集合中最后一条记录的 id 非常昂贵。
Is there a way to optimize this query so it uses the count variable $priorRecordsCnt
but i don't need to fetch all the records just to obtain the last value?有没有办法优化这个查询,所以它使用计数变量
$priorRecordsCnt
但我不需要获取所有记录来获取最后一个值?
The limit
clause takes two arguments - an optional offset and the row count. limit
子句采用两个 arguments - 一个可选的偏移量和行数。 Instead of using $priorRecordsCnt
as the record count, you should use it as the offset, and limit the record count to 1:与其使用
$priorRecordsCnt
作为记录数,不如使用它作为偏移量,并将记录数限制为 1:
select id
from wallactions
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY)
order by id desc LIMIT $priorRecordsCnt, 1
-- Here ---------------------------------^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.