SQL多表查询

目录

1.连接查询

2.嵌套查询不相关子查询

3.总结:

4.相关子查询

5.EXISTS表示存在量词


1.连接查询

--查询每个学生的学号、姓名、选修课程名及成绩
select sc.sno,sname,cname,grade
   from student,course,sc
   where student.sno=sc.sno and course.cno=sc.cno

2.嵌套查询不相关子查询

书写思路:先写内层,再写外层
执行流程:先执行内层,得到中间结果,外层利用中间结果进行后续查询,从而得到最终结果

--查询所有选修了c001号课程的学生姓名
select sname
     from student
     where sno in  --in或逻辑
         (select sno from sc
          where cno='c001')
select sname
          from student
          where sno=
             (select sno from sc
             where cno='c001' and student.sno=sc.sno)
select sname 
		from student 
		where exists(
			select * from sc where student.sno=sc.sno and cno='c001')--cno=001的sno传出去到student(这是不相关查询方式)
--查询计算机系年龄最小的学生姓名和年龄。
               
           select sname,sage
           from student
           where sage=
            ( select MIN(sage) from student--中间结果的为计算机的最小年龄19
               where sdept='计算机') and sdept='计算机'--外层找出年龄为19而且还是计算机系的,因为其他系也有19岁的人
               
           --等价于
           select sname,sage
           from student
           where sage<=all  --all代表所有,any代表某一个
            ( select sage from student--中间结果的为计算机的最小年龄
               where sdept='计算机') and sdept='计算机'
--查询其他系中比信息管理系所有学生年龄都大的学生姓名。

             select sname,sage,sdept from student
             where  sage>
               (select MAX(sage) from student
              where sdept='信息管理') and sdept!='信息管理'
              
              --等价于
             select sname from student
             where  sage>all
               (select sage from student
              where sdept='信息管理') and sdept<>'信息管理'

 3.总结:

1.不相关子查询的内层查询返回结果为单值,进行where条件构建嵌入时,使用关系运算符
2、不相关子查询的内层查询返回结果为多值,进行where条件构建嵌入时,使用in或关系运算符与any及all组合使用

4.相关子查询

 --书写思路:先写外层,再写内层
--执行流程:外层向内层传值(通过where条件传值),内层才可以执行(类比与循环的嵌套执行流程)

--查询每个学生超过他所有选修课程平均成绩的课程号

      select sno,cno from sc sc1
      where grade>
        (
           select AVG(grade) from sc sc2
           where sc2.sno=sc1.sno --传值
        )

5.EXISTS表示存在量词

EXISTS表示存在量词:只关心内层查询是否有结果,若有。则exists为真,否则为假
内层查询的目标为*

--查询选修“c002”号课程的学生姓名。(使用带有EXISTS谓词的子查询完成)

    select sname
    from student
    where exists   --not exists:内层查询是否有结果,若有。则exists为假,否则为真
    (
       select  * from sc
       where sc.sno=student.sno and cno='c002'
    )
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值