MySQL查询语句——子查询(1)# 子查询简述

一:子查询的特点:

  1. 子查询可被嵌套在 select,insert,update,delete 等语句中
  2. 大多数情况下子查询充当中间结果集角色
  3. 子查询可进行嵌套,且根据内存及表达式复杂程度不同,嵌套限制也不同
  4. 任何可使用表达式的地方,都可以使用子查询,只要他返回的是单个值

二:子查询的分类:

  1. 按返回值的数量可分为:标量子查询,多值子查询
  2. 按子查询对外部依赖性:独立子查询,相关子查询
  3. 按比较运算符的不同性:IN,EXISTS,ANY,SOME,ALL等多种形式

三:子查询的使用:

  1. 首先创建两个表(学生表和教师表)
    # 创建学生表
    mysql> create table tb_student(
        -> stu_ID long,
        -> class varchar(5),
        -> score int
        -> );
    Query OK, 0 rows affected (0.23 sec)
    
    # 创建教师表
    mysql> create table tb_teacher(
        -> tea_ID long,
        -> class varchar(5),
        -> age int
        -> );
    Query OK, 0 rows affected (0.49 sec)
  2. 将一些值插入到表中
    insert into tb_student values(1, "A", 20);
    
    insert into tb_student values(2, "A", 30);
    
    insert into tb_student values(3, "A", 70);
    
    insert into tb_student values(4, "B", 60);
    
    insert into tb_student values(5, "B", 70);
    
    insert into tb_student values(6, "B", 80);
    
    insert into tb_teacher values(1, "A", 25);
    
    insert into tb_teacher values(2, "B", 40);
  3. 准备工作完毕,接下来进行子查询练习
  • 例一:各班教师ID及其班级平均分数
    mysql> select tea_ID,
        -> (select avg(score) from tb_student as s where s.class = t.class group by class)
        -> as Avg from tb_teacher as t;
    +--------+---------+
    | tea_ID | Avg     |
    +--------+---------+
    | 1      | 40.0000 |
    | 2      | 70.0000 |
    +--------+---------+
    2 rows in set (0.00 sec)
  • 例二:各班级教师年龄及其班级及格人数(60为及格线)
    mysql> select age,
        -> (select count(*) from tb_student as s where s.class = t.class && s.score >= 60 group by class)
        -> as Count from tb_teacher as t order by Count desc;
    +------+-------+
    | age  | Count |
    +------+-------+
    |   40 |     3 |
    |   25 |     1 |
    +------+-------+
    2 rows in set (0.00 sec)

     

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值