如何在MySQL中查询当前数据的上下记录?

 我来答
耀光一坦格利安d425
推荐于2019-08-13 · TA获得超过7618个赞
知道小有建树答主
回答量:75
采纳率:97%
帮助的人:32.9万
展开全部

如果ID是主键或者有索引,可以直接查找:

方法一,查询上一条记录的SQL语句(如果有其他的查询条件记得加上other_conditions以免出现不必要的错误):1select * 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以免出现不必要的错误):1select * 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以免出现不必要的错误))1select * from table_a where id = (select <a href="http://www.baidu.com/swd=max&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1d9PjIP1Rvuy7hn1NBrAuW0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpAbmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1csnHDkrj6srj04rj64PH0LPj6" target="_blank" class="baidu-highlight">max</a>(id) from table_a where id < {$id} [and other_conditions]) [and other_conditions];

查询下一条记录的SQL语句(如果有其他的查询条件记得加上other_conditions以免出现不必要的错误):1select * from table_a where id = (select min(id) from table_a where id > {$id} [and other_conditions]) [and other_conditions]。

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式