一、表结构:
Student学生表(学号、姓名、性别、年龄、编辑)
Course课程表(课程编号、课程名称)
sc选课表(选课编号、学号、课程编号、成绩)

二、题目
(1)写一个SQL语句,查询选修了“计算机原理”的学生学号和姓名
(2)写一个SQL语句,查询“小明”同学选修的课程名称
(3)写一个SQL语句,查询选修了5门课程的学生学号和姓名
三、建表语句
create table student(
stu_no int,
stu_name varchar(10),
-- sex char(1),
-- age int(3),
-- edit varchar(20) )
-- DEFAULT charset=utf8;
-- insert into student 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');
-- #rop 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);
四、表显示



五、三表连接的方法
1、三表连接内连接
格式:
select * from 表1 a INNER JOIN 表2 b on a.表1字段=b.表2字段
INNER JOIN 表3 c on 表2.关联字段=表3.关联字段
案例:
select * from student a INNER JOIN sc b on a.stu_no=b.stu_no
INNER JOIN course c on b.c_no=c.c_no

2、三表连接左连接
格式:
select * from 表1 a left JOIN 表2 b on a.表1字段=b.表2字段
left JOIN 表3 c on 表2.关联字段=表3.关联字段
案例:
select * from student a left JOIN sc b on a.stu_no=b.stu_no
left JOIN course c on b.c_no=c.c_no

2、三表连接右连接
格式:
select * from 表1 a right JOIN 表2 b on a.表1字段=b.表2字段
right JOIN 表3 c on 表2.关联字段=表3.关联字段
案例:
select * from student 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 表1 a, 表2 b,表3 c where 表1.字段1=表2.字段2
and表2.字段2=表3.字段3
案例:
select * from student a, sc b,course c where a.stu_no=b.stu_no
and b.c_no=c.c_no

5、先将两个表合起来,在和另一表连接
案例:
select * from (select a.*,sc_no,c_no,score from student a INNER JOIN sc b on a.stu_no=b.stu_no)s INNER JOIN course c on s.c_no=c.c_no ;
浙公网安备 33010602011771号