PageHelper-Spring-Boot-Starter 所产生的 count 很耗时间,怎么优化?

2022 年 3 月 17 日
 JasonLaw

我有一个方法是分页获取用户,方法如下:

PageHelper.startPage(pageNumber, pageSize);
List<UserPageResponse> userPageResponseList = userMapper.findBy(some condition);
return new PageInfo<>(userPageResponseList);

userMapper.findBy对应的 SQL 语句如下:

SELECT u.id,
       u.name,
       total_consumption_times, # 复杂的 count
       total_consumption_amount, # 复杂的 sum
       u.last_consumption_time
FROM user u
where ...
order by u.create_time desc;

我期望它产生的 count 语句是:

SELECT count(0)
FROM (SELECT 0
      FROM user u
      where ...) table_count;

但实际它产生的 count 语句如下,导致执行时间很长。

SELECT count(0)
FROM (SELECT u.id,
             u.name,
             total_consumption_times,  # 复杂的 count
             total_consumption_amount, # 复杂的 sum
             u.last_consumption_time
      FROM user u
      where ...) table_count;

怎么解决这个问题?🤕


一个相关的 issue:1.3.1 版本 count 问题 · Issue #121 · pagehelper/pagehelper-spring-boot

2593 次点击
所在节点    程序员
13 条回复
xiaowei0823
2022 年 3 月 17 日
导致时间很长的是 select * 而不是 select count(0) from select 吗?
taogen
2022 年 3 月 17 日
蹲一个答案
pelloz
2022 年 3 月 17 日
像这样的框架问题,你一下没法修复或者换框架,那么你直接自己写一个 count 的 mapper ,先按自己正确的方法获取 count ,然后指定 page 的时候不要 count 就行了。我要是你,就换 mybatis-plus 了...
xuanbg
2022 年 3 月 18 日
mybatis-plus 也不能解决 PageHelper 的这个 count 问题吧?正确的做法就是在有复杂查询的时候,抛开 PageHelper 自己写一个查询 count 的方法。PageHelper 只用在简单查询上面。
jorneyr
2022 年 3 月 18 日
我不喜欢用这些插件,都是直接多写一个 SQL 。
JasonLaw
2022 年 3 月 18 日
@xiaowei0823 #1 导致时间很长是因为内嵌的 select 包含复杂的聚合运算。
JasonLaw
2022 年 3 月 18 日
@pelloz #3 MyBatis-Plus 能够解决这个问题?怎么解决的?
agzou
2022 年 3 月 18 日
手动分页
justNoBody
2022 年 3 月 18 日
JasonLaw
2022 年 3 月 18 日
@justNoBody #9 我刚刚找到了,THX ,准备等一下整理到附言那里。
JasonLaw
2022 年 3 月 18 日
@taogen #2 可以看一下 9 楼 justNoBody 的回复。
taogen
2022 年 3 月 18 日
@JasonLaw #11 好的
silentsky
2022 年 3 月 18 日
很简单 不要统计总页数
PageHelper.startPage(pageNumber, pageSize, Boolean.FALSE);

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/841129

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX