子查询

子查询

  • 在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为子查询语句

主查询

  • 主要查询的对象,第一条 select 语句

主查询和子查询的关系

  • 子查询是嵌入到主查询中
  • 子查询是辅助主查询的,要么充当条件,要么充当数据源
  • 子查询是可以独立存在的语句,是一条完整的 select 语句

子查询分类

  • 标量子查询: 子查询返回的结果是一个数据(一行一列)
  • 列子查询: 返回的结果是一列(一列多行)
  • 行子查询: 返回的结果是一行(一行多列)
  • 表级子查询: 返回的结果是多行多列

标量子查询

例1:查询班级学生的平均年龄

查询班级学生平均年龄
select avg(age) from students

查询大于平均年龄的学生
select * from students where age > 21.4167

select * from students where age > (select avg(age) from students);

例2:查询王昭君的成绩,要求显示成绩

学生表中查询王昭君的学号
select studentNo from students where name = '王昭君'

成绩表中根据学号查询成绩
select * from scores where studentNo = '001'

select * from scores where studentNo = (select studentNo from students where name = '王昭君')

列级子查询

例3:查询18岁的学生的成绩,要求显示成绩

学生表中查询18岁的学生的学号
select studentNo from students where age=18

成绩表中根据学号查询成绩
select * from scores where studentNo in ('002','006')

select * from scores where studentNo in (select studentNo from students where age=18)

行级子查询

例4:查询男生中年龄最大的学生信息

select * from students where sex='男' and age=(select max(age) from students)

select * from students where (sex,age)=('男',30)

select * from students where (sex,age) = (select sex,age from students where sex='男' order by age desc limit 1)

表级子查询

例5:查询数据库和系统测试的课程成绩

select 
    * 
from 
    scores s
inner join 
    (select * from courses where name in ('数据库','系统测试')) c
on s.courseNo = c.courseNo

子查询中特定关键字使用

  • in 范围

    • 格式: 主查询 where 条件 in (列子查询)
  • any | some 任意一个

    • 格式: 主查询 where 列 = any (列子查询)
    • 在条件查询的结果中匹配任意一个即可,等价于 in
  • all

    • 格式: 主查询 where 列 = all(列子查询) : 等于里面所有
    • 格式: 主查询 where 列 <>all(列子查询) : 不等一其中所有
select * from students where age in (select age from students where age b
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值