我想返回某条记录所在页面的页码。我使用条件查询返回所有的分页结果,所以我无法根据记录的id确定它所在的页面。我怎么解决这个问题?
我在网上找了很久。但是没有用。请帮助或尝试提供一些想法如何实现这一目标。
我的临时解决方案是查询每个页面的记录,直到它包含我需要的记录,但是这样做会导致查询变慢。
ps:我使用的是 MySQL 数据库。
我想返回某条记录所在页面的页码。我使用条件查询返回所有的分页结果,所以我无法根据记录的id确定它所在的页面。我怎么解决这个问题?
我在网上找了很久。但是没有用。请帮助或尝试提供一些想法如何实现这一目标。
我的临时解决方案是查询每个页面的记录,直到它包含我需要的记录,但是这样做会导致查询变慢。
ps:我使用的是 MySQL 数据库。
假设您有一条带有某种 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注释中并将其标记为本机查询。