【性能优化】MybatisPlus:优化查询速度之SQL替换Service
⽂章⽬录
【性能优化】Mybatis Plus:优化查询速度之 SQL 替换 Service
1、Service 接⼝问题
下⾯是原先的 Service 实现类代码,有门店 ID、订单状态、查询时间段,然后查出了所有的结果,继续使⽤ java8 的特性获取汇总结果,随着项⽬的推移,数据量越来越⼤,这种⽅式是不可取的,随便都能上⼏⼗秒查不出来,导致请求超时,下⾯我们就来优化⼀下这个⽅法
2、SQL 优化
先把上⾯的⽅法都转换成 SQL 语句的写法,得到下⾯的 5 个查询 SQL
select sum(A.pay_money) originPrice,count(A.id) countOrder,sum(A.pay_money) payMoney
from biz_order_info A
sql语句优化方式where A.`status`=der_status =2and A.store_id =1;
select sum(A.pay_money) smPayMoney
from biz_order_info A
where A.`status`=der_status =2and A.store_id =1and A.pay_way =1;
select sum(A.pay_money) rlPayMoney
from biz_order_info A
where A.`status`=der_status =2and A.store_id =1and A.pay_way =2;
select sum(A.pay_money) sjPayMoney
from biz_order_info A
where A.`status`=der_status =2and A.store_id =1and A.pay_way =3;
select sum(A.pay_money) xjPayMoney
from biz_order_info A
where A.`status`=der_status =2and A.store_id =1and A.pay_way =4;
然后整理⼀下代码,通过union all连接,最简单的⽅法,后端使⽤ List 来接收返回值,有⼀定的可⾏性
select*from(
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1)
union all
(select count(A.id)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1)
union all
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1)
union all
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1and A.pay_way =1)
union all
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1and A.pay_way =2)
union all
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1and A.pay_way =3)
union all
(select sum(A.pay_money)'value'from biz_order_info A where A.`status`=der_status =2and A.store_id =1and A.pay_way =4)
) X;
查询结果这样的
当我放到项⽬中时,发现还有查询条件,时间段,如果上⾯的 SQL 加上时间段,将会变的⾮常臃肿且难维护,所以上⾯的 SQL 报废了,不能使⽤,继续优化 SQL
-- 最开始的SQL
select A.*
from biz_order_info A
where A.`status`=der_status =2;
-- 初步汇总,拿到3个我们需要的值
select sum(A.pay_money),count(A.id),sum(A.pay_money)
from biz_order_info A
where A.`status`=der_status =2;
问题来了,怎么在已经查询出的结果中分⽀付⽅式汇总数据?
这⾥我使⽤的是 sum + case when 结构,分类汇总数据,再次优化 SQL
select sum(A.pay_money) originPrice,count(A.id) countOrder,sum(A.pay_money) payMoney,
sum(case A.pay_way when'1'THEN A.pay_money ELSE0END) smPayMoney,
sum(case A.pay_way when'2'THEN A.pay_money ELSE0END) rlPayMoney,
sum(case A.pay_way when'3'THEN A.pay_money ELSE0END) sjPayMoney,
sum(case A.pay_way when'4'THEN A.pay_money ELSE0END) xjPayMoney
from biz_order_info A
where A.`status`=der_status =2
查询结果
接下来随便⼀箱,有两种⽅式处理业务逻辑了
⽅法⼀:后台使⽤ Vo 实体类直接接收
⽅法⼆:使⽤ Map 接收
下⾯是测试结果,Service 操作性能提升了 75.61% ,所以以后不要查询所有的数据优化后的接⼝代码
不要⼀次性查询所有表数据
⼀次性 SQL 解决的问题,就不要写 Service ⽅法了
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论