select count(0)或者select count(*)等非常慢的优化(二)

涉及到mysql的explain命令,如果不了解的可以点击

如果执行

select count(0) from crm_customer

数据量比较大的情况下会得好几秒,几十万数据要执行10秒也见过,电脑原因,网络原因各种原因,总之就是因为InnoDB的原因,具体的网上去查吧,很多,这里只关注问题。

而几乎每个列表显示页都需要总行数,因为分页要根据总行数来计算页数,这样慢没人受得了,那为之奈何呢?

以下内容对数据量要求不是很精确的地方很有用,比如说你的系统某列表功能只需要显示100页数据,多的不用显示出来等情况下,而对于要精确根据总行数来分页什么的慎用,因为不是精确数。

explain select count(0) from crm_customer

执行时间是0.0035s

几秒跟0.0035秒的区别不用说什么,我们想办法取出这个结果中的rows作为表数据总行数替代select count(*)的结果不就可以了么,再次强调下不是精确结果,可能比真正的行数少,也可能比真正的行数多,误差上千不稀奇。

那么我们来处理这个结果,先将结果抽取对应的实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExplainResult implements Serializable {
    private int id;

    private String selectType;

    private String table;

    private String partitions;

    private String type;

    private String possibleKeys;

    private String key;

    private String keyLen;

    private String ref;

    private int rows;

    private int filtered;

    private String Extra;

}

xml的映射文件

<resultMap id="ExplainResultMap" type="com.xxx.entity.ExplainResult">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="select_type" property="selectType" jdbcType="VARCHAR"/>
        <result column="table" property="table" jdbcType="VARCHAR"/>
        <result column="partitions" property="partitions" jdbcType="VARCHAR"/>
        <result column="type" property="type" jdbcType="VARCHAR"/>
        <result column="possible_keys" property="possibleKeys" jdbcType="VARCHAR"/>
        <result column="key" property="key" jdbcType="VARCHAR"/>
        <result column="key_len" property="keyLen" jdbcType="VARCHAR"/>
        <result column="ref" property="ref" jdbcType="VARCHAR"/>
        <result column="rows" property="rows" jdbcType="INTEGER"/>
        <result column="filtered" property="filtered" jdbcType="INTEGER"/>
        <result column="Extra" property="Extra" jdbcType="VARCHAR"/>
</resultMap>

<select id="selectCount" resultMap="ExplainResultMap">
       explain select count(0) from crm_customer
</select>

实现类

@Override
public PageInfo<CrmCustomer> selectByPage(int page, int limit) {
        page = page * limit;
        List<CrmCustomer> customers= crmCustomerMapper.selectByPage(page, limit);
        PageInfo<CrmCustomer> pageInfo = new PageInfo<>(customers);
        ExplainResult explainResult = crmCustomerMapper.selectCount();
        int count = explainResult.getRows();
        pageInfo.setTotal(count);
        return pageInfo;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值