1. 多表查询
内连接(取两表的交集)
-
多表查询实际上就是计算笛卡尔积
-
多表查询就是通过把两个表排列组合, 把所有的可能性都列出来, 再通过筛选选出所需的记录
-
比如现在有两个表 学生表和班级表如下
-
我们要找出所有 42 班的学生的名字
select student.student_name
from student, class
where class.class_name = 'java42'
and student.class_Id = class.class_Id;
- 此外还有另一种写法 使用到了 join on
select student.student_name
from student
join class on class.class_name = 'java42'
and student.class_Id = class.class_Id;
1.2.1内连接练习
- 查询许仙同学的所有成绩
select student.name, score.score
from student join score
on student.id = score.student_id
where student.name = ' 许仙';
- 查询所有同学的总成绩,及同学的个人信息
select student.id, student.name,
student.qq_mail, sum(score.score)
from student join score
on student.id = score.student_id
group by student_id;
- 查询所有同学的成绩,及同学的个人信息
(包含课程名字的成绩)
select student.id, student.name,
score.score, course.id, course.name
from student
join score
on student.id = score.student_id
join course
on score.course_id = course.id;
外连接
-
外连接分为左外连接和右外连接 简称左连接和右连接
-
我们有以下两张表 学生表中的 4 号在成绩表中没有对应的成绩 , 成绩表中的 3 号在学生表中没有对应的学生
1. 左连接
- 如果我们用左连接查询会是以下的结果
2. 右连接
- 如果我们用右连接查询会是以下的结果
自连接
- 显示所有“计算机原理”成绩比“Java”成绩高的成绩信息
select * from score s1
join score s2
on s1.student_id = s2.student_id
where s1.course_id = 1
and s2.course_id = 3
and s2.score > s1.score;