Jump to content

Query Next & Previous In Sequence


Canman2005

Recommended Posts

Hi all

 

I have a table in a SQL database called "webitems" which looks like

 

ID    TITLE      LEVEL

1    home        65

2    about      234

3    contact    94

4    legal        21

5    services    157

 

What I want to do is to take an ID number, for example ID number 3 (contact) and return the next row in the LEVEL sequence, so for ID number 3, the LEVEL is 94, so it would return ID number 5 (services) as its the next number in the LEVEL sequence.

 

If ID number 1 (home) was selected, then because its LEVEL value is 65, it would look for the next one in the sequence and return it, in this instance, ID number 3 would be returned, as the value in LEVEL is 94, which is the next in the LEVEL seqence.

 

Does that make sense?

 

If anyone can help, could you also tell me how can I also reverse it, so rather than the next LEVEL in the sequence, it would show the previous one in the sequence.

 

For the next in sequence, I did try

 

SELECT * FROM `webitems` WHERE `level` > '94' ORDER BY `level` ASC LIMIT 1

 

and

 

SELECT * FROM `webitems` WHERE `level` < '94' ORDER BY `level` ASC LIMIT 1

 

for the reversed one

 

But that seems to sometimes return an incorrect result, so I guess its wrong.

 

Can anyone help?

 

Thanks a million in advance

 

Dave

Link to comment
https://forums.phpfreaks.com/topic/53927-query-next-previous-in-sequence/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.