且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MySQL中使用单个查询查找上一条和下一条记录?

更新时间:2023-01-29 08:55:21

您需要更改ORDER BY:

SELECT * FROM table WHERE `id` > 1556 ORDER BY `id` ASC LIMIT 1
UNION 
SELECT * FROM table WHERE `id` < 1556 ORDER BY `id` DESC LIMIT 1

这可以确保在获得最高结果之前,id字段的顺序正确.

This ensures that the id field is in the correct order before taking the top result.

您还可以使用MIN和MAX:

You can also use MIN and MAX:

SELECT
    * 
FROM
    table 
WHERE 
    id = (SELECT MIN(id) FROM table where id > 1556) 
    OR id = (SELECT MAX(id) FROM table where id < 1556)

应该注意的是,尽管不建议在生产代码中使用SELECT *,所以请在SELECT语句中命名您的列.

It should be noted that SELECT * is not recommended to have in production code, though, so name your columns in your SELECT statement.