6)表连接
1、内连接:符合关联条件的记录被检索出来,不符合条件的过滤掉;
两张表内连接格式:
select 字段列表 from 表1 [inner] join 表2 on 关联条件;
初始两张表中数据:
现需要将学生表中姓名、学号和班级表中的班级号放在一张表中;
select student.student_no,student.student_name,classes.class_name from student inner join classes on student.class_no = classes.class_no;
可以看到上述表中,由于表中没有一个不匹配的字符,所有都显示出来;
接下来我们将在表中新增加两项;让其不能匹配;
然后再执行与上述相同的内连接命令时,结果表与之前相同;这就是内连接,不会将不匹配的项显示出来;
此处,为方便书写,还可以将字段列表起别名,但是注意:表一旦命名别名,在当前语句中,就只能使用别名了,不能使用原表名;两张表中,没有重名的字段可以直接使用字段,不需要前面加表名或别名;
select s.student_no,s.student_name,c.class_name from student s join classes c on s.class_no = c.class_no;
下面这种就是错误的书写:
对于两种表中不相同的字段名可以直接写字段名,可以省略前缀的表名;
select student_no,student_name,class_name from student s join classes c on s.class_no = c.class_no;
三表连接:
select 字段列表 from 表1 join 表2 on 关联条件1 join 表3 on 关联条件2;
向choose空表中插入数据;
这儿我偷懒,直接加减当前日期;方便后续时间排序用;若插入失败,多试几次,加减时间可能溢出了,貌似只能对秒起作用?
insert into choose values(null,'2023001',2,40,now()), (null,'2023001',1,50,now()-10), (null,'2023002',3,60,now()+20), (null,'2023002',2,70,now()+1), (null,'2023003',1,80,now()-9), (null,'2023004',2,90,now()-12), (null,'2023005',3,null,now()-14), (null,'2023005',1,null,now()+5);
插入 完数据,就可以进行表连接了:三表连接的注意先后顺序;
关联条件:student.student_no=choose.student_no;course.course_no=choose.course_no;
#三表连接:学号、姓名、课程、成绩; select student.student_no 学号,student.student_name 姓名,course.course_name 课程名称,choose.score 成绩 from student join choose on student.student_no=choose.student_no join course on course.course_no=choose.course_no;
2、外连接:外连接 结果集 = 内连接结果集 + 匹配不上的记录;
1) 左外连接结果集 = 内连接结果集 + 左表匹配不上的记录;
select 字段列表 from 左表 left [outer] join 右表 on 关联条件;
例如:学生和班级列表:
select s.student_no,s.student_name,c.class_name from student s left join classes c on s.class_no = c.class_no;
由上图可以看出,左外连接是将左表中没有匹配的项也列出来了-----名字为 老六,没有分配班级;
2)右外连接结果集 = 内连接结果集 + 右表匹配不上的记录;
select 字段列表 from 左表 right [outer] join 右表 on 关联条件;
例如:将上述左外连接改为右外连接;
select s.student_no,s.student_name,c.class_name from student s right join classes c on s.class_no = c.class_no;
可以看出将左表中没有匹配的项列出来了---第一项,2023测控1班;