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.
I had the same problem as Dan, so I used his answer and improved it.
First select the row index, nothing different here.
Now use two separate queries. For example if the row index is 21, the query to select the next record will be:
To select the previous record use this query:
Keep in mind that for the first row (row index is 1), the limit will go to -1 and you will get a MySQL error. You can use an if-statement to prevent this. Just don't select anything, since there is no previous record anyway. In the case of the last record, there will be next row and therefor there will be no result.
Also keep in mind that if you use DESC for ordering, instead of ASC, you queries to select the next and previous rows are still the same, but switched.
My solution to get the next and previews record also to get back to the first record if i'm by the last and vice versa
I'm not using the id i'm using the title for nice url's
I'm using Codeigniter HMVC
Select top 1 * from foo where id > 4 order by id asc
This is universal solution for conditions wiht more same results.
If you have an index column, say id, you can return previous and next id in one sql request. Replace :id with your value