[英]MySQL - find N prev and next entries given an ID and order clause
我有这个结构
ID Value Price
1 a 10
2 b 30
3 c 30
4 d 20
5 e 5
6 f 40
我有一个 select 来获取按价格排序的清单
SELECT * FROM table ORDER BY Price ASC
这给了我
ID Value Price
5 e 5
1 a 10
4 d 20
2 b 30
3 c 30
6 f 40
现在在我的 web 页面上,用户单击ID=2
的项目并想要了解它的一些详细信息。 但是,在这个详细信息页面上,我想按顺序显示 N 个上一个和下一个项目。 给定ID
和ORDER BY
子句,如何获得 N 个上一个和下一个项目?
drop table if exists mytable;
create table mytable (ID serial primary key, Value char(1), Price int);
insert into mytable values
(1,'a',10),
(2,'b',30),
(3,'c',30),
(4,'d',20),
(5,'e',5),
(6,'f',40);
select t2.id, t2.value, t2.price
from (
select id, row_number() over (order by price asc) as rownum
from mytable
) as t1
join (
select *, row_number() over (order by price asc) as rownum
from mytable
) as t2
on t2.rownum between t1.rownum-2 and t1.rownum+2
where t1.id = 2
order by price asc;
Output,在 MySQL 8.0.29 测试:
+----+-------+-------+
| id | value | price |
+----+-------+-------+
| 1 | a | 10 |
| 4 | d | 20 |
| 2 | b | 30 |
| 3 | c | 30 |
| 6 | f | 40 |
+----+-------+-------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.