多测师肖sir__三表___14.0
Student学生表(学号、姓名、性别、年龄、编辑)
Course课程表(编号、课程名称)
sc选课表(选课编号、学号、课程编号、成绩)
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');
-- #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 student;
select * from course;
select * from sc;
学生表: student; as a 表
选课表: as b 表
成绩表 as c表
三表连接的格式:
1、
格式:select * from 表1,表2,表3 where 表1.关联字段1=表3.关联字段3 AND 表2.关联字段2=表3.关联字段 3;
案例:select * from student as a ,course as b,sc as c where a.stu_no=c.stu_no AND b.c_no=c.c_no ;
图:
2、
三表内连接
#内连接
格式:
select * from 表1 INNER JOIN 表3 on 表1.关联字段1=表3.关联字段3 INNER JOIN表2 on 表2.关联字段2=表3.关联字段3
案例:select * from student as a INNER JOIN sc as c on a.stu_no=c.stu_no INNER JOIN course as b on b.c_no=c.c_no
3、三表左连接
格式:select * from 表1 left JOIN 表3 on 表1.关联字段1=表3.关联字段3 left JOIN表2 on 表2.关联字段2=表3.关联字段3
案例:select * from student as a left JOIN sc as c on a.stu_no=c.stu_no left JOIN course as b on b.c_no=c.c_no
4、三表右连接
格式:格式:select * from 表1 right JOIN 表3 on 表1.关联字段1=表3.关联字段3 right JOIN表2 on 表2.关联字段2=表3.关联字段3
案例:select * from student as a right JOIN sc as c on a.stu_no=c.stu_no right JOIN course as b on b.c_no=c.c_no
5、先合两表在和一表
格式:select * from (select * from 表1 right JOIN 表3 on 表1.关联字段1=表3.关联字段3 ) 临时表s inner 表2 on 临时表. 字段3=表2.字段2
案例:
select * from (select c.stu_no,stu_name,sex,age,edit,sc_no,c_no,score from student as a right JOIN sc as c on a.stu_no=c.stu_no ) s INNER JOIN course as b on s.c_no =b.c_no ;
==========================================
练习:
1)写一个SQL语句,查询选修了“计算机原理”的学生学号和姓名
方法:SELECT a.stu_no,a.stu_name from student a,course b,sc c where a.stu_no=c.stu_no and b.c_no=c.c_no AND c_name='计算机原理'
(2)写一个SQL语句,查询“小明”同学选修的课程名称
方法: SELECT c_name FROM student a,course b,sc c where a.stu_no=c.stu_no and b.c_no=c.c_no and stu_name='小明'
(3)写一个SQL语句,查询选修了5门课程的学生学号和姓名
方法1:SELECT a.stu_name,a.stu_no FROM student a,course b,sc c where a.stu_no=c.stu_no and b.c_no=c.c_no group by stu_name HAVING count(stu_name)=5,
方法2:
SELECT a.stu_name ,a.stu_no FROM student a,course b,sc c where a.stu_no=c.stu_no and b.c_no=c.c_no group by a.stu_no HAVING count(a.stu_no)=5
注意点:
1、在合表的过程中右重复列的情况,请注意显示的字段
select * from (select a.*,sc_no,c_no ,score from student a inner JOIN sc c on a.stu_no=c.stu_no)s ,course b where s.c_no=b.c_no