一、业务场景
通常,我们在业务代码中要判断某张表是否存在数据,持久化查询的业务代码通常会这样写
int count = testMapper.countByExample(example);
if(count > 0){
//有数据, do something
}else{
//没有数据, do other thing
}
mabatis-generator自动生成的xml中,countByExample通常如下
<select id="countByExample" parameterType="org.test.db.domain.ucUserExample" resultType="java.lang.Long">
select count(*) from uc_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
数据不多的时候,count() 是完全ok的啦。然而,当我们这张uc_user表特别大时候,select count(*)真的太慢了!
假设,uc_user表中有25w+的数据行, 我们执行 count(),再SHOW PROFILES,可看到如下
二、优化查询
我们可以使用下面语句来判断某表是否存在数据,我们再用show profiles看看效果。发现快了好多!!!后续,我们业务代码中可以愉快的执行啦~(mapper文件对应的返回类型可能要替换为object类型)
select 1 from test.uc_user LIMIT 1;
效果图