SQL Serve---嵌套查询

定义

嵌套查询:主要用于复杂的查询中。在SQL语言中,一个Select From Where语句称为一个查询块,将一个查询块嵌套在另一个查询的Where子句或Having短语中的查询称为嵌套查询

子查询的类型
使用别名的子查询
使用INNOT IN的子查询
使用比较运算符的子查询
使用ANYALL修改的比较运算符
使用EXISTSNOT EXISTS的子查询

--列出tb_student表中和“陈凯”年龄相同的学生的学号和姓名

年龄:year(getdate())-year(birthday)

--列出tb_student表中和“陈凯”年龄相同的学生的学号和姓名
 select s1.sno,s1.sn 
 from tb_student as s1
 where year(getdate())-year(birthday)=
(select  year(getdate())-year(birthday) 
from tb_student  as s2 
where s2.sn=‘陈凯’)

--在选修c02课程成绩大于该课平均成绩的学生学号,姓名,成绩

--在选修c02课程成绩大于该课平均成绩的学生学号(),姓名,成绩
 select s.sno,sn,s1.score
 from 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 c
  Where  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 ) 

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值