子 查 询
子查询 (内查询) 在主查询之前一次执行完成。子查询的结果被主查询(外查询)使用 。子查询类型还分单行子查询和多行子查询,子查询的使用:子查询要包含在括号内和将子查询放在比较条件的右侧
例如:
select sname
from student
where sno>(select sno
from student
where sname='匡明')
这段代码的意思是找出大于匡明的sno的人等的名字
- 单行子查询
单行子查询只返回一行,使用单行比较操作符有‘=’,‘>’, ‘>=’,‘<=’,‘<’ ‘<>’
例如:查询选修编号为“3-105”且成绩高于选修编号为“3-245”课程的同学的Cno、Sno和Degree.
select sno,cno,degree
from score
where degree>(select max(degree)from score where cno='3-245')
and cno='3-105'
在子查询中使用使用组函数和 HAVING 子句
例如:查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
select avg(degree) as avgdegree
from score
group by cno
having cno='3-105';
在子查询中是非法使用子查询
例如:
select sname
from student
where sno=(select sno from student
where class=95033)
这个例子是不可以查询出来的,得出来的结果
2.多行子查询
IN 等于列表中的任意一个
ANY 和子查询返回的某一个值比较
ALL 和子查询返回的所有值比较
例如:使用ANY
查询选修编号为“3-105“课程且成绩至少高于选修编号为“3-245”的同学的Cno、Sno和Degree,并按Degree从高到低次序排序。
select *
from score
where cno='3-105'
and degree >ANY(select degree from score where cno='3-245')
例如:使用ALL
查询选修编号为“3-105”且成绩高于选修编号为“3-245”课程的同学的Cno、Sno和Degree.
select cno,sno,degree from score where cno='3-105' and degree>all
(select degree from score where cno='3-245') order by degree desc
例如:使用IN
SELECT *
FROM Student
WHERE sno NOT IN (select sno from student WHERE sname LIKE '王%')
注意:如果在IN的后面加上null,就会出现空值