假设您有一条带有某种 id 的记录,并且当表格按某些标准排序时,您可以知道它出现在表格中的什么位置,您可以使用分析函数来做到这一点。在给定页面大小的情况下,您可以根据该值轻松计算它出现的页面。
示例架构 (MySQL v8.0)
create table example (
id integer not null primary key,
text varchar(20));
insert into example(id, text) values (23,"Alfred");
insert into example(id, text) values (47,"Berta");
insert into example(id, text) values (11,"Carl");
insert into example(id, text) values (42,"Diana");
insert into example(id, text) values (17,"Ephraim");
insert into example(id, text) values (1,"Fiona");
insert into example(id, text) values (3,"Gerald");
查询
select *
from (
select id, text,
count(*) over (order by text) cnt // change the order by according to your needs
from example
// a where clause here limits the table before counting
) x where id = 42; // this where clause finds the row you are interested in
| id | text | cnt |
| --- | ----- | --- |
| 42 | Diana | 4 |
为了将它与 Spring Data JPA 一起使用,您将此查询放在 @Query 注释中并将其标记为本机查询。