The primary key output of such a select might look more random and thus less succeptable to mathematical locating (since some results would be filtered, out, e.g. with a where active=1):select primary_key from table where primary_key > (34-5) order by primary_key where active=1 limit 11;30-=34=-8083100113125126127128129请注意,由于示例 where 条件(例如因为有许多非活动项目)导致主键中的间隙,我不再获得最接近的 5 以上和 5 以下,而不是我得到最接近的下方 1 和上方最接近的 9.Note how due to the gaps in the primary keys caused by the example where condition (for example becaseu there are many inactive items), I'm no longer getting the closest 5 above and 5 below, instead I'm getting the closest 1 below and the closest 9 above, instead.推荐答案如果您使用一种编程语言运行两个查询,有很多方法可以做到这一点,但这里有一种方法可以在一个 SQL 查询中完成:There's a lot of ways to do it if you run two queries with a programming language, but here's one way to do it in one SQL query:(SELECT * FROM table WHERE id >= 34 AND active = 1 ORDER BY id ASC LIMIT 6)UNION(SELECT * FROM table WHERE id < 34 AND active = 1 ORDER BY id DESC LIMIT 5)ORDER BY id ASC这将返回上面的 5 行、目标行和下面的 5 行.This would return the 5 rows above, the target row, and 5 rows below. 这篇关于如何选择任意行的相邻行(在 sql 或 postgresql 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-30 19:46