如何从表中查找prev和next id记录

时间:2010-08-15 09:01:20

标签: mysql

如何从给出id的表中了解prev id值和下一个id值?

就像ia有id = 5表格中的recod然后我想知道prev id值和下一个id值

3 个答案:

答案 0 :(得分:1)

如果id是自动增量INT字段,

SELECT * FROM tablename WHERE id < 5 ORDER by ID DESC LIMIT 0,1;

SELECT * FROM tablename WHERE id > 5 ORDER by ID ASC LIMIT 0,1;

应该做的。

答案 1 :(得分:1)

也许就像......

SELECT MAX(id) AS previous
    FROM my_table
    WHERE id < 5;

SELECT MIN(id) AS next
    FROM my_table
    WHERE id > 5;

会得到你想要的东西。

答案 2 :(得分:0)

SELECT * FROM table WHERE id = ( SELECT min(id) FROM table WHERE id > id )
SELECT * FROM table WHERE id = ( SELECT max(id) FROM table WHERE id < id )