Question : How do I get the next and previous record of one target record in a set of records?

Alright, I have an inbox interface that lets my users read their messages. The inbox is paginated by SQL LIMIT and OFFSET.... the OFFSET is calculated by the records being displayed times the page number saught..... pretty standard.

So a user clicks on a particular message, and I have Previous | Next navigation for user to move through his messages.... what I need is a way for me to grab only the previous conversation_id of the previous and next record from THIS record. And if it so happens that THIS record is the first message in the inbox, then the previous message needs to then be the last message in the inbox. The same if THIS message is the last, the Next button needs to roll to the first message in the inbox.

RIght now I have:

$sql_2 = "SELECT conversation_id FROM app_get_account_inbox_funk('" . $this->account_id . "');";

and from the PHP I grab the previous and next depending upon where THIS conversation_id is found in the returning array. This is okay, but I can imagine that once a users has a 1000 or more messages in his inbox this will definitely slow down the page.

Any ideas? Also, I use postgres. Thanks.

Answer : How do I get the next and previous record of one target record in a set of records?

Assuming that the ids are in ascending order try using this querys

- NEXT
$sql = "select *  FROM app_get_account_inbox_funk where account_id="  . $this->account_id ." AND conversation_id>".$this->conversartion_id." order by conversation_id ASC LIMIT 1";
- PREVIOUS
$sql = "select *  FROM app_get_account_inbox_funk where account_id="  . $this->account_id ." AND conversation_id<".$this->conversartion_id." order by conversation_id DESC LIMIT 1";
And in the case of the last/first message
- LAST
$sql = "select *  FROM app_get_account_inbox_funk where account_id="  . $this->account_id ." order by conversation_id DESC LIMIT 1";
- FIRST
$sql = "select *  FROM app_get_account_inbox_funk where account_id="  . $this->account_id ." order by conversation_id ASC LIMIT 1";
Random Solutions  
 
programming4us programming4us