且构网

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

用mysql选择围绕id的行之前和之后

更新时间:2023-12-03 18:42:22

一种可能的解决方案是

  • 计算每个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