连接查询
交叉连接
不带谓词的连接,较少使用(广义笛卡尔积,无实际意义)
select Student.*,Sc.* from Student,Sc
select Student.*,Sc.* from Student Cross Join Sc
等值连接
在交叉连接后添加筛选条件(对交叉后的笛卡尔积进行筛选)
select Student.*,Sc.* from Student,Sc where Student.Sno=Sc.Sno
自身连接
找出每门课的先修课
select a1.Cname,a2.Cname from Course a1,Course a2 where a1.Cpno = a2.Cno
找出先修课的先修课号(禁止套娃)
select a1.Cno,a2.Cpno from Course a1,Course a2 where a1.Cpno = a2.Cpno
找出同时选修了2号和3号得而学生学号
select a.Sno from Sc a,Sc b where a.Sno=b.Sno
and a.Cno <> b.Cno--不等于
and a.Cno=2 and b.Cno=3
嵌套查询
将一个查询块嵌套在另一个查询块的where或having条件中
查找选修2号课程的学员
select Sname from Student where in --外层查询(如果返回不是结果集,in可以换成=)
(select Sno from Sc where Cno = 2)--内层查询
不相关子查询:先执行内层查询,然后将内层的结果集作为条件允许外层查询
相关子查询(内层结果依赖外层)先执行外层,然后执行内层
select Sname from Student where Exisis
(select * from Sc where Cno = 2 and Sno = Student.Sno)
子查询限制: 不能使用order by语句
ANY和ALL(返回值都是单值)
ANY--任意
ALL --所有
带有EXISTS的子查询(是否存在,与not搭配使用)
不返回结果集,只返回 T 或 F ,select结果不为空(1或者多)则为T
例,查询选修了全部课程的学生(查询没有一门课程不选修的学生的姓名)
selcet Sname from Student S where
(select * from Course C where
NOT EXISTS (select * from Sc where S.Sno = Sno And C.Cno =Cno))
集合查询
使用交、并、差对查询集合进行操作(部分库没有提供并和差)
参加交的表必须具有相同的列数,对应数据项也必须相同
select Sno from Sc where Cno=1
UNION
select Sno from Sc where Cno=2