MySQL中的标量子查询,列子查询,行子查询

标量子查询,列子查询,行子查询都属于where子查询,也就是说都写在where之后


### 标量子查询 #### 概念 > 子查询得到的结果是一个数据(一行一列) #### 语法 `select * from 数据源 where 条件判断 =/<> (select 字段名 from 数据源 where 条件判断);` > 查询到的结果就只有一个结果 #### 案例 - 知道一个学生的姓名 : 小生,想知道她在哪个班级(班级名字) - 通过学生表获取到她所在的班级ID - 通过班级ID获取到班级名字 - 需求决定主查询 - 条件决定子查询 `select * from my_class where class_id = (select class_id from my_student where stu_name = '小生');`

列子查询

概念

子查询得到的结果是一列数据(一列多行)

语法

主查询 where 条件 in (列子查询);

案例
  • 获取已经有学会说呢过在班的所有班级名字
    • 找出学生表中所有的班级ID
    • 找出班级表中对应的名字
      select name from my_class where class_id in (select class_id from my_student);

行子查询

概念

返回的结果是一行多列

语法

主查询 where 条件[(构造一个行元素)] = (行子查询);

案例

  • 获取班级上年龄最大,且身高最高的学生
    • 求出班级年龄最大的值
    • 求出班级身高最高的值
    • 求出对应的学生
      select * from my_student where (stu_age,stu_height) = (select max(stu_age),max(stu_height) from mu_student);
发布了145 篇原创文章 · 获赞 38 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/yehuaner33/article/details/100148980