X10nD
X10nD

Reputation: 22050

Get previous & next id value of mysql query

SELECT * FROM TableName WHERE name='test'

Once the above query is executed I want the previous and next id values. Ofcourse they will not be incremental. How can I get the next and previous ids based on the where condition.

Upvotes: 0

Views: 2433

Answers (3)

Sumit Bijvani
Sumit Bijvani

Reputation: 8179

SELECT
    * 
FROM
    TableName 
WHERE 
    id = (SELECT MIN(id) FROM TableName where id > 2) 
    AND id = (SELECT MAX(id) FROM TableName where id < 2)

OR you can use Limit

SELECT * FROM TableName WHERE `id` > 2 ORDER BY `id` ASC LIMIT 1
UNION 
SELECT * FROM TableName WHERE `id` < 2 ORDER BY `id` DESC LIMIT 1

Upvotes: 1

Devang Rathod
Devang Rathod

Reputation: 6736

try below

 select * from Tablename where name = 'test' AND id = (select min(id) from Tablename  where id > 4) OR id = (select max(id) from Tablename  where id < 4)

Upvotes: 1

ArthasNed_StarkGimli
ArthasNed_StarkGimli

Reputation: 42

I believe you can use mysql_data_seek() if you are using php

http://php.net/manual/en/function.mysql-data-seek.php

Upvotes: 0

Related Questions