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];
相關文章
相關標籤/搜索