--多表查询
--查询选修了课程名为“信息系统”的学生学号和姓名
select sno,sname
from student
where sno in(
select sno
from course,sc
where cname='信息系统' and
course.cno = sc.cno);
--或者
select sno,sname
from student
where sno in(
select sno
from sc
where cno in(
select cno
from course
where cname='信息系统'));
--或者
select student.sno,sname --由于student和sc里面均有sno,所以需要指明是哪个表里面的sno
from student,sc,course
where student.sno=sc.sno and --进行连接的时候一定要说明连接的列
course.cno = sc.cno and
cname='信息系统';
--或者
select student.sno,sname
from student,sc
where cno in(
select cno
from course
where cname='信息系统' ) and
student.sno = sc.sno;
--找出每个学生超过他选修课程平均成绩的课程号。
select sno,cno
from sc x --x和y均为别名
where grade>=
(select avg(grade)
from sc y
where x.sno = y.sno); --为什么不需要distinct???
--查询其他系中比信息系任意一个(其中某一个)学生年龄小的学生姓名和年龄
select sname,sage
from student
where sage<any
(select sage
from student
where sdept='IS')and
sdept!='IS';
--查询所有选修了1号课程的学生姓名。
select sname
from student,sc
where student.sno=sc.sno and
student.sno in
(select sc.sno
from sc
where cno=1
);
--或者
select sname
from student
where exists
(select *
from sc
where student.sno=sc.sno and
cno=1);
----查询没有选修了1号课程的学生姓名。
select sname
from student
where not exists
(select *
from sc
where student.sno=sc.sno and
cno=1);
--查询与“刘晨”在同一个系学习的学生。
select sno,sname
from student x
where exists
(select *
from student y
where x.sdept=y.sdept and
y.sname='刘晨'
);
--查询选修了全部课程的学生姓名 没有一门课是他不选的 比较的是集合,而集合是DBMS在底层实现的
select sname
from student
where not exists --没有一门课
(select *
from course
where not exists --没选
(select *
from sc
where sno = student.sno and --比较的是这门课该学生有没有选
cno = course.cno));
--查询至少选修了学生201215122选修的全部课 程的学生号码。 不存在这样的课程y,学生201215122选修了y,而学生x没有选
select distinct sno
from sc x
where not exists --不存在课程
(select *
from sc y
where y.sno=21 and
not exists
(select *
from sc z
where x.sno=z.sno and
z.cno=y.cno));
--查询计算机科学系的学生及年龄不大于19岁的学生
select sno
from student
where sdept='CS'
union
select sno
from student
where sage<=19
order by sno;--order by语句一定是在最后
--或者
select sno
from student
where sdept='CS' or
sage<=19;
--查询计算机科学系的学生与年龄不大于19岁的学生的交集(INTERSECT) 。
select sno
from student
where sdept='CS'
intersect
select sno
from student
where sage<=19;
--或者
select sno
from student
where sdept='CS' and
sage>19;
--查询计算机科学系的学生与年龄不大于19岁的学生的差集。
select sno
from student
where sdept='CS'
except
select sno
from student
where sage<=19;
--或者
select sno
from student
where sdept='CS' and
sage>19;
数据库多表查询
最新推荐文章于 2022-04-06 22:53:40 发布