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 ) 

相关推荐

  1. MySQL修炼手册6:子查询入门:在查询嵌套查询

    2024-04-25 03:36:01       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 03:36:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 03:36:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 03:36:01       82 阅读
  4. Python语言-面向对象

    2024-04-25 03:36:01       91 阅读

热门阅读

  1. C++ day2

    C++ day2

    2024-04-25 03:36:01      38 阅读
  2. 通过Redis实现一个异步请求-响应程序

    2024-04-25 03:36:01       35 阅读
  3. Vue通俗概念理解

    2024-04-25 03:36:01       38 阅读
  4. InfluxDB v1.8

    2024-04-25 03:36:01       37 阅读
  5. 2024 极术通讯-生成式AI的发展现状与未来趋势

    2024-04-25 03:36:01       35 阅读