0
SELECT * FROM TableName WHERE name='test'

执行上述查询后,我想要上一个和下一个 id 值。当然,它们不会是增量的。如何根据 where 条件获取下一个和上一个 id。

4

3 回答 3

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

或者你可以使用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
于 2013-03-04T09:58:54.327 回答
1

试试下面

 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)
于 2013-03-04T09:48:13.153 回答
0

我相信如果您使用 php,您可以使用 mysql_data_seek()

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

于 2013-03-04T09:55:47.087 回答