https://blog.51cto.com/u_15115717/3432924
建表语句:
===================================
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);
============================================
select * from student ;
select * from course ;
select * from sc ;
============================================
学生表
课程表
选课表
Student学生表(学号、姓名、性别、年龄、编辑) as a
Course课程表(课程编号、课程名称) as b
sc选课表(选课编号、学号、课程编号、成绩) as c
============================================
题目:
(1)写一个SQL语句,查询选修了“计算机原理”的学生学号和姓名
(2)写一个SQL语句,查询“小明”同学选修的课程名称
(3)写一个SQL语句,查询选修了5门课程的学生学号和姓名
============================================
三表连接:
方法一:三表隐藏内连接
格式:select * from 表1 , 表2 ,表3 where 表1.关联的字段=表3.关联字段 and 表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
方法二:三表普通内连接
格式:
select * from 表1 INNER JOIN 表3 on 表1.关联的字段=表3.关联字段 inner join 表2 on 表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
方法三:三表普通左连接
格式:select * from 表1 left JOIN 表3 on 表1.关联的字段=表3.关联字段 left join 表2 on 表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
方法四:三表普通右连接
格式:select * from 表1 right JOIN 表3 on 表1.关联的字段=表3.关联字段 right join 表2 on 表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
方五:先合两表,在两表合并成一表与第三个表合并
select s.stu_no ,s.stu_name from ( select a.stu_no ,stu_name,c_no from student a ,sc c where a.stu_no=c.stu_no )s ,course as b where s.c_no=b.c_no
============================================
解题思路:
(1)写一个SQL语句,查询选修了“计算机原理”的学生学号和姓名
条件: c_name =“计算机原理” course表
结果:stu_no , name student表
方法一:
SELECT a.stu_no, a.stu_name from student a join sc c on a.stu_no = c.stu_no join course b on c.c_no = b.c_no where b.c_name = "计算机原理"
(2)写一个SQL语句,查询“小明”同学选修的课程名称
方法一:
SELECT b.c_name FROM student a ,course b , sc c WHERE a.stu_no=c.stu_no and b.c_no=c.c_no and a.stu_name="小明";
方法二:
select c.stu_name,b.c_name from sc a join course b on a.c_no = b.c_no join student3 c on a.sc_no = c.stu_no where c.stu_name = '小明' ;
方法三:
(3)写一个SQL语句,查询选修了5门课程的学生学号和姓名