我想返回某个记录所在的页面的页码。我使用条件查询返回所有分页结果,因此无法根据记录的id确定页面的位置。我该如何解决这个问题?
我在网上搜索了很长时间。但没用。请帮助或尝试给一些想法如何实现这一点。
我的临时解决方案是查询每个页面的记录,直到它包含我需要的记录为止,但是这样做会导致查询速度慢。
ps:我正在使用MySQL数据库。
发布于 2020-05-09 05:52:16
假设您有一个带有某种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一起使用它,您将此查询放入@Query注释中,并将其标记为本机查询。
https://stackoverflow.com/questions/61692124
复制相似问题