用mysql选择围绕id的行之前和之后 [英] Select before and after rows around id with mysql
本文介绍了用mysql选择围绕id的行之前和之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用mySQL获取围绕ID的ID.
I need to get the IDs around an ID with mySQL.
示例:
ID:
2, 4, 5, 9, 11, 15, 19, 22, 25
例如,我需要知道ID 9周围的5个ID. 查询应返回:
I need to know the 5 IDs around the ID 9, for example. The query should return:
4, 5, 9, 11, 15
谢谢!
推荐答案
一种可能的解决方案是
- 计算每个ID减去ID的绝对值.
- 对结果进行排序,并将结果集限制为5条记录.
SQL语句
SELECT ABS(ID - 9), *
FROM MyTable
ORDER BY
ABS(ID - 9)
LIMIT 5
编辑 (向ypercube表示此解决方案可能存在的缺陷)
如果要从左侧获取2个id,从右侧获取2个id,则可以按以下方式调整该语句
If the intent is to get 2 id's from the left and two id's from the right, the statement can be adjusted as follows
SELECT * FROM MyTable WHERE ID <= 9 ORDER BY ID DESC LIMIT 3
UNION ALL
SELECT * FROM MyTable WHERE ID > 9 ORDER BY ID ASC LIMIT 2
这篇关于用mysql选择围绕id的行之前和之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文