数据查询(二)
二.连接查询
等值查询
1.查询每个学生及其选修课程的情况
select student.* ,SC.*
from Student,SC
where Student.Sno = SC.Sno;
自身连接
2.查询每一门课的间接先修课
select first.Cno,second.Cno //first second为Course的别名
from Course first,Course second
where first.Cpno = second.Cpno;
复合条件连接
3.查询选修2号课程且成绩在90分以上的所有学生
select Student.Sno,Sname
from Student,SC
where Cno = '2' and Grade > 90 and Student.Sno = SC.Sno;
4.查询每个学生的学号、姓名、选修的课程名及成绩
select Student.Sno,Sname,Cname,Grade
from Student,Course,SC
where Student.Sno = SC.Sno and SC.Cno = Course.Cno;
二.嵌套查询
select Sname
from Student
where Sno in(
select Sno
from SC
where Cno = '2'
) ;
带有in谓词的子查询
5.查询与Larry在同一个系的学生姓名
select Sname
from Student
where Sdept in(
select Sdept
from Student
where Sname = 'Larry'
);
6.查询选修了课程名为“信息系统”的学生学号和姓名
select Sno,Sname
from Student
where Sno in(
select Sno
from SC
where Cno in(
seelct Cno
from Course
where Cname = '信号与系统'
)
);
//或者是
select Student.Sno,Sname
from Studnet,SC,Course
where SC.Sno = Student.Cno and SC.Cno = Course.Cno and Cname = '信号与系统';
带有比较运算符的查询
7.查询与Larry在同一个系的学生姓名
由于每一个学生只在一个系学习,因此该例可以用比较运算符=查询:
select Sname
from Student
where Sdept = (
select Sdept
from student
where Sname = 'Larry'
);
8.查询每个学生超过他选修课程平均成绩的课程号
select Cno
from SC x//这是一个相关子查询
where grade > (
select avg(grade)
from SC y
where y.Sno = x.Cno
);
9.查询其他系中比计算机系所有学生的年龄都小的学生姓名和年龄
select Sname,Sage
from student
where sage <= (
select min(sage)
from student
where Sdept = 'CS'
)
and Sdept <> 'CS';
带有exists谓词的子查询
10.查询所有选修了1号课程的学生姓名
select Sname
from SC,student
where exists(//如果是没有选修,则改为 where not exists...
select *
from SC
where Sno = student.Sno and Cno = '1'
);
11.查询选修了全部课程的学生姓名
该题目可以等价转换为:查询一个学生,没有一门课程是他不选修的。
select Sname
from student
where not exists(
select *
from Course
where not exists(
select *
from SC
where Cno = Course.Cno and Sno = student.Sno
)
);
12.查询至少选修了学生2014213000选修的全部课程的学生学号
该题目可以等价转换为:不存在这样的课程y,2014213000选修了y,而学生x没有选。
select distinct Sno
from SC SCX
where not exists(
select *
from SC SCY
where SCY.Sno = '2014213000' and not exists(
select *
from SC SCZ
where SCZ.Sno = SCX.Sno and SCZ.Cno = SCY.Sno));
//说实话,这个我也不是很懂。
四.集合查询
集合的操作主要包括并操作**union、交操作insersect、差操作**except
注:集合操作的查询结果的列数必须相同,对应项的数据类型也必须相同。
13.查询计算机系的学生及年龄不大于19岁的学生
select *
from student
where Sdept = 'CS'
union
/*
*UNION可以将多个查询结果合并,并自动去掉重复元组
*/
select *
from student
where Sage < 19;
14.查询选修了课程1或选修了课程2的学生的学号
select Sno
from SC
where Cno = '1'
union
select Sno
from SC
where Cno = '2';
//敲完这篇博客我就去复习,讲真。