一、多表查询
表结构:
student
| id | name | gender | age |
|---|---|---|---|
| 1 | aaa | 男 | 20 |
| 2 | aaa | 男 | 22 |
| 3 | aaa | 女 | 21 |
| 4 | ccc | 男 | 22 |
| 5 | ccc | 女 | 21 |
score
| id | student_id | course_id | score |
|---|---|---|---|
| 1 | 1 | 1 | 85.0 |
| 2 | 1 | 2 | 92.0 |
| 3 | 2 | 1 | 78.0 |
| 4 | 2 | 2 | 88.0 |
| 5 | 3 | 1 | 90.0 |
| 6 | 3 | 2 | 95.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,可以全部查出来再比较。