我有一個表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