且构网

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

MySQL-选择一行-然后相对于所选行,下一行和上一行

更新时间:2023-01-21 18:39:43

执行此操作的最简单方法是利用以下事实:您的ID尽管不是连续的,但它们是以升序排列的.

The simplest way to do this is to exploit the fact that, although not continuous, your ids are in ascending order.

例如:

SELECT * FROM Table WHERE id = 8

UNION
--Select the first item less than 8
SELECT * FROM Table WHERE id = (SELECT MAX(id) FROM Table WHERE id < 8)

UNION
--select the first item greater than 8
SELECT * FROM Table WHERE id = (SELECT MIN(id) FROM Table WHERE id > 8)

如果您只知道字符串,则:

If you only know the string, then:

DECLARE _id INT

SELECT _id = id FROM Table WHERE value = 'i_like_women'

然后,您可以简单地将此_id输入到上面的查询中,而不是8.

Then you can simply feed this _id into the above query, instead of 8.

请注意,您不需要使用`来划分表名和列名.

Note you don't need to use ` to demarcate the table and column names.