
定义
嵌套查询:主要用于复杂的查询中。在SQL语言中,一个Select From Where语句称为一个查询块,将一个查询块嵌套在另一个查询的Where子句或Having短语中的查询称为嵌套查询。
 子查询的类型 
 
 使用别名的子查询 
 
 使用IN和NOT IN的子查询 
 
 使用比较运算符的子查询 
 
 使用ANY或ALL修改的比较运算符 
 
 使用EXISTS和NOT EXISTS的子查询 
 
 

--列出tb_student表中和“陈凯”年龄相同的学生的学号和姓名
年龄:year(getdate())-year(birthday)
--列出tb_student表中和“陈凯”年龄相同的学生的学号和姓名select s1.sno,s1.sn from tb_student as s1where year(getdate())-year(birthday)=
(select  year(getdate())-year(birthday) 
from tb_student  as s2 
where s2.sn=‘陈凯’)
--在选修c02课程成绩大于该课平均成绩的学生学号,姓名,成绩
--在选修c02课程成绩大于该课平均成绩的学生学号(),姓名,成绩select s.sno,sn,s1.scorefrom tb_student s,
(select sno,score 
from tb_score
where cno='c02' and score>(select  avg(score)
from tb_score  where cno='c02'))as s1
where s.sno=s1.sno
in:返回值是一个以及一个以上的 
 
 --查询软件 3班同学所选所有课程的名称 
 
select  cn from  tb_course
where cno IN(select cno  from tb_ score 
where  left(sno,10)=‘2015010103')
 ¯ 查询不选c02课程的学生的学号、姓名、系别 
 
select sno,sn,dept from  tb_student
where sno NOT IN (select sno from tb_score  where cno=‘c02')
--查询考取最高分的学生的学号、课号、课名,成绩
  select sno,s.cno,cn,score from  tb_score s,tb_course cWhere  s.cno=c.cno and score =(select max(score) from tb_score)
 -- 年龄高于平均年龄的所有学生的学号和姓名 
 
 
select sno,sn 
from  tb_student
where year(getdate())-year(birthday) > (select avg(year(getdate())-year(birthday) )from tb_student)
注意:
>all(1,2,3) :表示大于3(表示大于最大值)
>any(1,2,3): 表示大于最小值
 -- 查找某门课程成绩高于或等于任何一门课程最高成绩的学生学号 
 
select distinct sno,cno,score
from tb_score
Where score >= any 
(select max(score)from    tb_score 
group by cno)
 --在 tb_student 表中查询 tb_score 表中有成绩的学生学号和 姓名 
 
select  sno,sn  from tb_student
where  sno = 
any(select  sno  from tb_score)
 -- tb_score 表中 c01 和 c02两科成绩都大于60分的同学学号。 
 
 
select  sno  
from  tb_score 
where  cno='c01'  and  score>60  and sno in    
(  select  sno from  tb_score where   cno='c02' and score>60 )