Skip to content

2025-10-13-联合查询

背景

内连接

查询"唐三藏"同学的成绩

SQL
select student.`name`, score, course.`name`
from student 
join score on student.student_id = score.student_id 
join course on course.course_id = score.course_id
where student.`name` = '唐三藏';

查询所有同学的总成绩,及同学的个人信息

SQL
select student.student_id, student.`name`, sum(score.score) 
from student 
join score on student.student_id = score.student_id 
group by student.student_id

外连接

查询没有参加考试的同学信息

SQL
-- 由于缺考的学生是有学生信息,但是没有考试信息,需要保留学生信息,
-- 所以要连接学生,那么就用 left join 就是保留学生数据
select student.* from student
left join score on student.student_id = score.student_id
where score.course_id is null;

自连接

这个是适用于行与行之间的比较

显示所有"MySQL'成绩比"JAVA"成绩高的成绩信息

SQL
select * from score as s1, score as s2
where s1.student_id = s2.student_id and 
s1.course_id = 1 and s2.course_id = 3 and s1.score < s2.score

子查询

不推荐使用,因为一般一条SQL语句是要比较简单的,而这个是违背了初衷

查询与"不想毕业"同学的同班同学

SQL
select name from student where name != '不想毕业' and class_id in (
  select class_id from student where name = '不想毕业'
);

合并查询

了解即可

查询student表中 id < 3 的同学和student1表中的所有同学