使用当当sharding-jdbc分表,Mysql LIMIT分页的优化方案

当当sharding-jdbc官方文档,分表分页的性能问题以及优化方案 http://shardingjdbc.io/1.x/docs/02-guide/subquery/

通过记录上次查询结果的最后一条记录的ID进行下一页的查询:

SELECT * FROM t_order WHERE id > 100000 LIMIT 10

因此,衍生出另一个问题,如何获取上次查询结果的最后一条记录的ID?

暂时的SQL写法有两种:

1)

	<select id="getPreviousSequenceID" resultType="java.lang.String">
		select max(temp.SequenceID) from (
			select e.SequenceID
			  from tableXXXXXX e
			 where e.UserID = #{userId}
				<if test="startDate != null" >
					<![CDATA[ AND e.Adddate >= #{startDate} ]]>
				</if>
				<if test="endDate != null" >
					<![CDATA[ AND e.Adddate <= #{endDate} ]]>
				</if>
			  ORDER BY SequenceID ASC
			  limit #{preTotalCount}
		) temp
	</select>

2)

        <select id="getPreviousSequenceID" resultType="java.lang.String">
		select SequenceID
		  from tableXXXXXX 
		 where UserID = #{userId}
			<if test="startDate != null" >
				<![CDATA[ AND Adddate >= #{startDate} ]]>
			</if>
			<if test="endDate != null" >
				<![CDATA[ AND Adddate <= #{endDate} ]]>
			</if>
   		 ORDER BY SequenceID ASC
		 limit #{preTotalCount}, 1
	</select>

参考下面文章,里面有详细分析max和limit 10000,1 两种方法的比较

http://database.51cto.com/art/201005/200395.htm

文章的结果如下:

第1句执行结果.100 rows in set (0.23) sec

第2句执行结果.100 rows in set (0.19) sec

自己也测试过,结果如下:


只是依据简单的测试结果,limit 10000,1的性能好于用max,MySQL5.0中Mysql limit性能应该作了优化。

下面是查询的SQL用于替代limit:

	<select id="queryUserCommisionList" resultType="com.tuandai.ms.aqs.domain.ExtendEarnRecord">
		select SequenceID, ID, UserID AS userId
		  from tableXXXX
		 where UserID = #{userId}
			<if test="startDate != null" >
				<![CDATA[ AND Adddate >= #{startDate} ]]>
			</if>
			<if test="endDate != null" >
				<![CDATA[ AND Adddate <= #{endDate} ]]>
			</if>

			<if test="beginSequenceID != null and beginSequenceID != '' "  >
				<![CDATA[ and SequenceID >= #{beginSequenceID} ]]>
			</if>
		<!--
			sharding-jdbc不支持这种类型的子查询 SELECT COUNT(*) FROM (SELECT * FROM t_order o WHERE o.id IN (SELECT id FROM t_order WHERE status = ?))
		-->
		<!--
			<if test="beginIndex != null and beginIndex != '' "  >
				<![CDATA[ and SequenceID >=  ]]> (select MAX(e.SequenceID) from tableXXXX e where e.UserID = #{userId} LIMIT #{beginIndex}, 1)
			</if>
		-->

		 ORDER BY SequenceID ASC
		 limit #{pageSize}
	</select>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值