我有一个表foo
与其主键id
和一些其他列。 我的目标是找到行id=3
和id=4
行和id=6
和id=7
行id=5
- 如果我想找到2个最接近的前一行和下一行。如何获得表中特定行的最近n行?
如果只有一个或没有这样的行(例如对于id=2
只有前一行),我只想得到可能的行。
问题是可能有一些行丢失。
有没有常见的做法,使这样的查询?
我有一个表foo
与其主键id
和一些其他列。 我的目标是找到行id=3
和id=4
行和id=6
和id=7
行id=5
- 如果我想找到2个最接近的前一行和下一行。如何获得表中特定行的最近n行?
如果只有一个或没有这样的行(例如对于id=2
只有前一行),我只想得到可能的行。
问题是可能有一些行丢失。
有没有常见的做法,使这样的查询?
我会尝试以下方法:依次按
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2
SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
您可以到上面结合成以下:
SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
UNION
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2
这是一个可行的解决方案,通过对所有记录进行编号并获取行号比选定ID大2或更低的那些记录。
create table foo(id int); insert into foo values (1),(2),(4),(6),(7),(8),(11),(12);
-- using ID = 6 with rnum as ( select id, row_number() over (order by id) rn from foo ) select * from rnum where rn >= (select rn from rnum where id = 6) - 2 and rn <= (select rn from rnum where id = 6) + 2;
id | rn -: | -: 2 | 2 4 | 3 6 | 4 7 | 5 8 | 6
-- using ID = 2 with rnum as ( select id, row_number() over (order by id) rn from foo ) select * from rnum where rn >= (select rn from rnum where id = 2) - 2 and rn <= (select rn from rnum where id = 2) + 2;
id | rn -: | -: 1 | 1 2 | 2 4 | 3 6 | 4
dbfiddle here
我想这会适合你的描述。
Select * from table where id between @n-2 and @n+2 and id <> @n
的一种方式是这样的:
with your_table(id) as(
select 1 union all
select 2 union all
select 4 union all
select 5 union all
select 10 union all
select 11 union all
select 12 union all
select 13 union all
select 14
)
select * from (
(select * from your_table where id <= 10 order by id desc limit 3+1)
union all
(select * from your_table where id > 10 order by id limit 3)
) t
order by id
(以下10
是起点和3
是你想要n
行)
所以,如果只有一个上一行,那么你只需要一个下一行? (即使在开始时你想要5个上一行和5个下一行)? –
@OtoShavadze nope。在这种情况下,我需要一个上一行和下一个5。 – ivkremer