我有一个表foo
及其主键id
和其他一些列。
我的目标是找到包含id=3
和id=4
的行以及包含id=6
和id=7
的行,以及id=5
行 - 以防我想查找2个最接近的上一行和下一行。
如果只有一行或没有这样的行(例如id=2
只有前一行),我想只获得可能的行。
问题是可能缺少某些行。
是否有通常的做法来进行此类查询?
答案 0 :(得分:2)
我会尝试以下方法:
SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
接着是
SELECT * FROM table WHERE id <= ? ORDER BY id DESC 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
答案 1 :(得分:0)
这是一种可能的解决方案,它通过对所有记录进行编号并获取行号大于或小于所选ID的行数。
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
答案 2 :(得分:0)
我认为这符合您的描述。
Select * from table where id between @n-2 and @n+2 and id <> @n
答案 3 :(得分: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
行