mysql优化之N+1问题

周六收到老大通知说我之前写的两个接口因数据量过大有性能问题😔,快乐的周末就这么没了。当时写接口的时候光想着实现功能未考虑性能问题。嗨呀,那写的叫一个舒坦,很快啊,左一个if判断,右一个for循环,for循环里面再加几个QueryWrapper查询,最后再用一下stream过滤一下数据,畅快淋漓,贼顺畅,当时多顺畅现在重构接口就多苦逼。
在这里插入图片描述
mysql优化一些老生常谈的咱就不细说了,像什么索引,加索引的注意点,索引失效的情况,不要用select *查询,where后面不要进行非空判断之类的,大家都是工作一段时间的说话硬气点,今天来聊聊mysql优化之N+1的问题,说的可能不咋的,大家有兴趣可以B站找找视频看看,后面我也会看看视频然后再来补充这篇博客,今天主要是让大家有这个意识。😆😆
在这里插入图片描述
1.什么是N+1问题

A对象关联B对象,A对象进行列表展示时需显示B对象的关联属性,这样需要先用一条sql将N个A对象查询出来,再用N条sql将这些对象的关联属性查询出来。违背了减少数据库交互原则,影响性能。
  千万不要在for循环里面进行sql查询操作
  就像下面我当初写的破代码

        trainClassVoList.forEach(trainClassVo -> {
            CommOrgAudit commOrgAudit = commOrgAuditService.getOne(Wrappers.<CommOrgAudit>lambdaQuery().eq(CommOrgAudit::getDeptId, trainClassVo.getCreateDept()));
            if (commOrgAudit != null) {
                trainClassVo.setOrgName(commOrgAudit.getOrgName());
                trainClassVo.setOrgUnitName(commOrgAudit.getOrgUnitName());
                List<TrainClassStudent> trainClassStuList = trainClassStudentService.list(Wrappers.<TrainClassStudent>lambdaQuery().eq(TrainClassStudent::getClassId, trainClassVo.getId()));
                // 培训总人数
                Long trainStuMun = trainClassStuList.size() + 0l;
                // 已取证人数
                Long stuCertificateNum = 0l;
                for (TrainClassStudent trainClassStudent : trainClassStuList) {
                    List<ExamCert> stu = examCertService.getByStuId(trainClassStudent.getId());
                    if (stu.size() != 0) {
                        stuCertificateNum = stuCertificateNum + 1;
                    }
                }
                // 取证率%
                NumberFormat numberFormat = NumberFormat.getInstance();
                // 设置精确到小数点后2位
                numberFormat.setMaximumFractionDigits(2);
                if (stuCertificateNum != 0 && trainStuMun != 0) {
                    double x = stuCertificateNum * 1.0;
                    double y = trainStuMun * 1.0;
                    double fen = x / y;
                    String res = numberFormat.format(fen * 100);
                    trainClassVo.setEvidenceRate(res + "%");
                } else {
                    trainClassVo.setEvidenceRate("0%");
                }
                // 获取学时未完成人数
                long count = trainClassStuList.stream().filter(trainClassStudent -> trainClassStudent.getStudyStatus().equals("1")).count();
                trainClassVo.setTrainStuNoEndMun(count);
            }

2.解决方法

方法一:连接查询,在查询A对象的时候,将关联的B对象查询出来。缺点:1、连接的表增加,sql性能下降;2、如果N个A对象关联的是同一个B对象,会使结果集非常庞大,返回结果集需要消耗性能,并且影响排序性能。比如100个employee都关联dept id 1,本来dept的数据只需出现一次,这里为了避免N+1,重复出现100次。

方法二:A表中设置冗余字段。缺点:更新B表需要更新A表。更新A表时需要增加修改B对象属性的逻辑。这个方法最好别用,有时候会存在忘记更新数据的情况。

方法三:性能最佳,1+1查询。先用sql查出所有employee查询出,将他们关联的deptId放到一个set中,再发一条sql,deptid in set 将所有dept查出,之后在程序中将deptset 进入employee。
  下面是我重构的代码,展示部分

        List<Integer> deptIdList = trainClassVoList.stream().map(TrainClassVo::getCreateDept).collect(Collectors.toList());
        // 培训机构信息列表
        Map<Integer, Map<String, String>> map = new HashMap<>();
        if (deptIdList.size() > 0) {
            List<CommOrgAudit> commOrgAuditList = commOrgAuditService.getInfoByDeptIdList(deptIdList);
            commOrgAuditList.forEach(commOrgAudit -> {
                Map<String, String> orgMap= new HashMap<>();
                m.put("orgName", commOrgAudit.getOrgName());
                m.put("orgUnitName", commOrgAudit.getOrgUnitName());
                map.put(Integer.valueOf(commOrgAudit.getDeptId().toString()), m);
            });
        }

sql:

    <select id="getInfoByDeptIdList" parameterType="list" resultType="com.gl.train.api.entity.CommOrgAudit">
        SELECT
        coa.id,coa.dept_id,coa.org_name,coa.org_unit_name
        FROM
        comm_org_audit coa
        WHERE coa.dept_id in
        <foreach collection="list" separator="," open="(" close=")" item="item">
            #{item}
        </foreach>
    </select>
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值