2017-06-05 91 views
1

我有一個表foo與其主鍵id和一些其他列。 我的目標是找到行id=3id=4行和id=6id=7id=5 - 如果我想找到2個最接近的前一行和下一行。如何獲得表中特定行的最近n行?

如果只有一個或沒有這樣的行(例如對於id=2只有前一行),我只想得到可能的行。

問題是可能有一些行丟失。

有沒有常見的做法,使這樣的查詢?

+0

所以,如果只有一個上一行,那麼你只需要一個下一行? (即使在開始時你想要5個上一行和5個下一行)? –

+0

@OtoShavadze nope。在這種情況下,我需要一個上一行和下一個5。 – ivkremer

回答

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 
0

這是一個可行的解決方案,通過對所有記錄進行編號並獲取行號比選定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

0

我想這會適合你的描述。

Select * from table where id between @n-2 and @n+2 and id <> @n 
0

的一種方式是這樣的:

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行)