tags:

views:

772

answers:

6

Say I have records with IDs 3,4,7,9 and I want to be able to go from one to another by navitagion via next/previous links. The problem is, that I don't know how to fetch record with nearest higher ID.

So when I have 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 whole result set and manualy iterating?

I'm using MySQL 5.

A: 

Select top 1 * from foo where id > 4 order by id asc

Gratzy
mysql doesn't support TOP
longneck
Top 1 * doesn't work in mysql.
Byron Whitlock
my ignorance sorry
Gratzy
Equivalent MySQL is "LIMIT 1": `select * from foo where id>4 order by id asc LIMIT 1`
mobrule
+2  A: 

next:

select * from foo where id = (select min(foo) where id > 4)

previous:

select * from foo where id = (select max(foo) where id < 4)
longneck
I think the subqueries should be (select min(id) from foo where id > 4) and (select max(id) from foo where id < 4).
fireeyedboy
you're right, i forgot the FROM clause. thanks for pointing it out. :)
longneck
+1  A: 
SELECT * FROM foo WHERE id>4 ORDER BY id LIMIT 1
Cem Kalyoncu
+1 I think this is the cleanest solution. But the LIMIT clause should come last: SELECT * FROM foo WHERE id > 4 ORDER BY id LIMIT 1
fireeyedboy
Fixed the limit position
Cem Kalyoncu
A: 

Maybe it is wrong guess but maybe what you need you might get using CURSOR

http://dev.mysql.com/doc/refman/5.0/en/cursors.html

MoreThanChaos
cursors will be overkill for this task.
Cem Kalyoncu
A: 

In addition to cemkalyoncu's solution:

next record:

SELECT * FROM foo WHERE id > 4 ORDER BY id LIMIT 1;

previous record:

SELECT * FROM foo WHERE id < 4 ORDER BY id DESC LIMIT 1;
fireeyedboy
A: 

You should handle that with and iterator object in your application.

Phillip Jacobs