我想返回某条记录所在的页面的页码。我使用条件查询返回所有的分页结果,所以我无法根据记录的id来确定它所在的页面。请问如何解决这个问题?
我在网上搜索了很久。但是没有用。请大家帮忙或试着给一些想法,如何实现。
我的临时解决方案是查询每个页面的记录,直到它包含我需要的记录,但这样做会导致查询速度慢。
ps.我使用的是MySQL数据库。我使用的是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
注解并将其标记为本地查询。