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.
All the above solutions require two database calls. The below sql code combine two sql statements into one.
next:
previous:
Optimising @Don approach to use only One Query
change CurrentArticleID with current article ID like
Here we have a way to fetch previous and next records using single MySQL query. Where 5 is the id of current record.
There's another trick you can use to show columns from previous rows, using any ordering you want, using a variable similar to the @row trick:
Apparently, the select columns are evaluated in order, so this will first select the saved variables, and then update the variables to the new row (selecting them in the process).
NB: I'm not sure that this is defined behaviour, but I've used it and it works.
Try this example.
Note: If value is not found then it will return null.
In the above example, Previous value will be Raja and Next value will be null because there is no next value.