mysql中的子查询有哪些_mysql中的子查询

一、子查询的分类

1. 按位置分为

where 子查询:子查询在where条件中

from 子查询:子查询在from后面

exists子查询:子查询在exists中

2. 按查询结果分为

标量子查询:查询结果有一行一列

列子查询:查询结果有一列多行

行子查询:查询结果有一行多列或多行多列

表子查询:查询结果有多行多列并且出现的位置在from之后

二、子查询详解

1. 标量子查询

-- 已知学生表my_stu和班级表my_class, 查询class001班中的所有学生,查询结果是一个ID,一行和列

select * from my_stu where class_id = (select id from my_class where c_name = 'class001');

2. 列子查询

-- 查询所有存在的班级内的学生

select * from my_stu where class_id in (select id from my_class);

-- 类似in的其他条件关键字, 都必须带 = 号

select * from my_stu where class_id = any(select id from my_class);  -- 等于其中任意一个就保留

select * from my_stu where class_id = some(select id from my_class); -- 等于其中一部分就保留

select * from my_stu where class_id = all (select id from my_class);   -- 等于其中所有的才保留

3. 行子查询

-- 查询学生中年龄最大且身高最高的

select * from my_stu where age = (select max(age) from my_stu) and height = (select max(height) from my_stu);  -- 常规查询

select * from my_stu where (age,height) = (select max(age),max(height) from my_stu);  -- 构造行元素来使用行子查询

4. 表子查询

-- 找出每个班最高的一个学生

select * from (select * from my_stu order by height desc) as s group by class;

5. exists子查询

exists接在where之后, 返回0或1.

select * from my_student where exists(select * from my_class where id = 1);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值