sql优化篇

79 阅读1分钟

一、多表查询

表结构:

student

idnamegenderage
1aaa20
2aaa22
3aaa21
4ccc22
5ccc21

score

idstudent_idcourse_idscore
11185.0
21292.0
32178.0
42288.0
53190.0
63295.0

具体代码:


@RestController
@RequestMapping("/oop")
public class OOPController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private ScoreService scoreService;

    @GetMapping("/stud")
    public List<String> findByStudName(@RequestParam("name") String name){

        List<String> resList = null;
        try {
            resList = new ArrayList<>();
            LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            studentLambdaQueryWrapper.eq(Student::getName, name);
            List<Student> list = studentService.list(studentLambdaQueryWrapper);

            // 实现1
            List<Score> listScore = scoreService.list();
            for (Score score : listScore) {
                for (Student student : list) {
                    if(score.getStudentId().equals(student.getId())){
                        resList.add(score.getScore().toString());
                    }
                }

            }

//            // 实现02
//            List<Integer> listId = new ArrayList<>();
//            for (Student student : list) {
//                listId.add(student.getId());
//            }
//            LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            scoreLambdaQueryWrapper.in(Score::getStudentId, listId);
//            List<Score> listScore = scoreService.list(scoreLambdaQueryWrapper);
//            for (Score score : listScore) {
//                resList.add(score.getScore().toString());
//            }

//            // 实现03
//            for (Student student : list) {
//                LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                scoreLambdaQueryWrapper.eq(Score::getStudentId, student.getId());
//                List<Score> listScore = scoreService.list(scoreLambdaQueryWrapper);
//                if(listScore != null){
//                    for (Score score : listScore) {
//                        resList.add(score.getScore().toString());
//                    }
//                }
//            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resList;
    }
}

注意: 对于多表联查,注意不要出现循环里面套sql,可以全部查出来再比较。