MySQL查询当前数据上一条和下一条的记录

若是ID是主键或者有索引,能够直接查找:sql

方法一:ide

查询上一条记录的SQL语句(若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误):spa

select * from table_a where id = (select id from table_a where id < {$id} [and other_conditions] order by id desc limit 1) [and other_conditions];

查询下一条记录的SQL语句(若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误):orm

select * from table_a where id = (select id from table_a where id > {$id} [and other_conditions] order by id asc limit 1) [and other_conditions];

方法二:索引

查询上一条记录的SQL语句((若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误))get

select * from table_a where id = (select max(id) from table_a where id < {$id} [and other_conditions]) [and other_conditions];

查询下一条记录的SQL语句(若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误):it

select * from table_a where id = (select min(id) from table_a where id > {$id} [and other_conditions]) [and other_conditions];
相关文章
相关标签/搜索