简体   繁体   中英

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.

试试下面

 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)
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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM