7.8学习笔记(多表的连接)

一、建表
表结构:
Student1学生表(学号、姓名、性别、年龄、编辑)
Course课程表(编号、课程名称)
sc选课表(选课编号、学号、课程编号、成绩)
(1)写一个SQL语句,查询选修了“计算机原理”的学生学号和姓名
结果:stu_no ,stu_name
条件:c_name= ” 计算机原理“
SELECT stu_no ,stu_name from (select a.* ,b.sc_no,b.c_no,b.score from student1 a inner JOIN sc b on a.stu_no=b.stu_no)s INNER JOIN course c on s.c_no=c.c_no where c_name="计算机原理"

(2)写一个SQL语句,查询“小明”同学选修的课程名称
结果:c_name
条件:stu_name="小明"
SELECT c_name from (select a.* ,b.sc_no,b.c_no,b.score from student1 a inner JOIN sc b on a.stu_no=b.stu_no)s INNER JOIN course c on s.c_no=c.c_no where stu_name="小明"

(3)写一个SQL语句,查询选修了5门课程的学生学号和姓名

SELECT stu_no,stu_name from (select a.* ,b.sc_no,b.c_no,b.score from student1 a inner JOIN sc b on a.stu_no=b.stu_no)s INNER JOIN course c on s.c_no=c.c_no group by s.stu_no HAVING count(s.stu_no)=5

create table student1(
stu_no int,
stu_name varchar(10),
sex char(1),
age int(3),
edit varchar(20) )
DEFAULT charset=utf8;
insert into student1 values
(1,'wang','男',21,'hello'),
(2,'小明','女',22,'haha2'),
(3,'hu','女',23,'haha3'),
(4,'li','男',25,'haha4');
create table course(
c_no int,
c_name varchar(10)
)
DEFAULT charset=utf8;

insert into course values
(1,'计算机原理'),
(2,'java'),
(3,'c'),
(4,'php'),
(5,'py');

drop table sc;

create table sc(
sc_no int,
stu_no int,
c_no int,
score int(3))
DEFAULT charset=utf8;
insert into sc values
(1,1,1,80),
(2,2,2,90),
(3,2,1,85),
(4,2,3,70),
(5,2,4,95),
(6,2,5,89);

二、分析表
select * from student1 ;
select * from sc ;
select * from course;

学生表:student1
stu_no stu_name sex age edit

学生编号 学生姓名 性别 年龄 编辑

sc :选修课表
sc_no stu_no c_no score
选修编号 学生编号 课程编号 分数

course 课程表
c_no c_name
课程编号 课程名称

三、连接方式:
(1)内连接 INNER JOIN
格式:
select * from 表1 别名 INNER JOIN 表2 别名2 on 表1.关联字段=表2 .关联字段 INNER JOIN 表3 别名3 on 表2.关联字段=表3.关联字段
如:
select * from student1 a INNER JOIN sc b on a.stu_no=b.stu_no INNER JOIN course c on b.c_no=c.c_no

隐藏内连接:

格式:select * from 表1 别名1 ,表2 别名2,表3 别名3 where 表1.关联字段1=表2.关联字段2 and
表2.关联字段2=表3.关联字段3

如:select * from student1 a ,sc b,course c where a.stu_no=b.stu_no and
b.c_no=c.c_no

(2)左连接 (left join)
格式:
select * from 表1 别名 left JOIN 表2 别名2 on 表1.关联字段=表2 .关联字段 left JOIN 表3 别名3 on 表2.关联字段=表3.关联字段
如:
select * from student1 a left JOIN sc b on a.stu_no=b.stu_no left JOIN course c on b.c_no=c.c_no

(3)右连接(right join)
格式:
select * from 表1 别名 right JOIN 表2 别名2 on 表1.关联字段=表2 .关联字段 right JOIN 表3 别名3 on 表2.关联字段=表3.关联字段

如:select * from student1 a right JOIN sc b on a.stu_no=b.stu_no right JOIN course c on b.c_no=c.c_no

(4)将两个合成一个表,在和第三个合并
格式:
SELECT * from (select * from 表1 别名 INNER JOIN 表2 别名2 on 表1.关联字段=表2 .关联字段 )s INNER JOIN 表 3 on 表2.关联字段=表3.关联字段

如:
第一步:将两个表合成一个表
select a.* ,b.sc_no,b.c_no,b.score from student1 a inner JOIN sc b on a.stu_no=b.stu_no
第二步:将合并的表,与第三表进行和表
SELECT * from (select a.* ,b.sc_no,b.c_no,b.score from student1 a inner JOIN sc b on a.stu_no=b.stu_no)s INNER JOIN course c on s.c_no=c.c_no

备注:重复列,再次运用,可以用
表名.* 显示一个表所有的内容,在填写另一个表的字段名

posted on 2026-07-08 17:56  小房子i  阅读(2)  评论(0)    收藏  举报

导航