Say I have records with IDs 3,4,7,9 and I want to be able to go from one to another by navigation via next/previous links. The problem is, that I don't know how to fetch record with nearest higher ID.
So when I have a record with ID 4, I need to be able to fetch next existing record, which would be 7. The query would probably look something like
SELECT * FROM foo WHERE id = 4 OFFSET 1
How can I fetch next/previous record without fetching the whole result set and manually iterating?
I'm using MySQL 5.
How to get next/previous record in MySQL & PHP?
My example is to get the id only
I think to have the real next or previous row in SQL table we need the real value with equal, (< or >) return more than one if you need to change position of row in a ordering table.
we need the value
$position
to search theneighbours
row In my table I created a column 'position'and SQL query for getting the needed row is :
for next :
for previous:
Using @Dan 's approach, you can create JOINs. Just use a different @variable for each sub query.
If you want to feed more than one
id
to your query and getnext_id
for all of them...Assign
cur_id
in your select field and then feed it to subquery gettingnext_id
inside select field. And then select justnext_id
.Using longneck answer to calc
next_id
:In addition to cemkalyoncu's solution:
next record:
previous record:
edit: Since this answer has been getting a few upvotes lately, I really want to stress the comment I made earlier about understanding that a primary key colum is not meant as a column to sort by, because MySQL does not guarantee that higher, auto incremented, values are necessarily added at a later time.
If you don't care about this, and simply need the record with a higher (or lower)
id
then this will suffice. Just don't use this as a means to determine whether a record is actually added later (or earlier). In stead, consider using a datetime column to sort by, for instance.