MySQL- 子查询的使用

MySQL
子查询的使用

什么是子查询

子查询是将一个 SELECT 语句的查询结果作为中间结果,供另一个 SQL 语句调用。
像这样:

-- 我们将学生表中的所有班级ID当做中间结果
select *from t_class where c_id in (select distinct c_id from t_student);

常用比较符

子查询最常用的用法:

non_subquery_operand comparison_operator (subquery)
其中操作符通常为
= > < >= <= <> != <=>

其他的都不说了,这里说下这个<=>,以前还真没用过
<=>和=比较类似,也是判断是否相等,相等返回1,不相等返回2

mysql> select 1<=>1,1<=>2;
+-------+-------+
| 1<=>1 | 1<=>2 |
+-------+-------+
|     1 |     0 |
+-------+-------+
1 row in set

mysql> select 1=1,1=2;
+-----+-----+
| 1=1 | 1=2 |
+-----+-----+
|   1 |   0 |
+-----+-----+
1 row in set

和=不一样的地方,是对NULL的支持,用<=>可以判断是否为null,而等号则是出现null,结果就为null

mysql> select 1<=>null,null<=>null,1=null,null=null;
+----------+-------------+--------+-----------+
| 1<=>null | null<=>null | 1=null | null=null |
+----------+-------------+--------+-----------+
|        0 |           1 | NULL   | NULL      |
+----------+-------------+--------+-----------+
1 row in set

any、in、some

在子查询中,in平时用的比较多,这个any、some,这里简单说下any和some

operand comparison_operator ANY (subquery)
operand comparison_operator SOME (subquery)
comparison_operator 可以为 = > < >= <= <> !=

any表示任意一个值,比如
> any () :表示大于any中任意一个值,即>子查询中最小值
< any(): 表示小于any中任意一个值,即<子查询中最大值
= any(): 和in一样
<> any():比较好玩儿,如果子查询返回多个值,<> any会返回所有值

select *from t_student 
where s_id > any(
    select s_id from t_student where s_id in (105,109,111)
);
>any
select *from t_student 
where s_id = any(
    select s_id from t_student where s_id in (105,109,111)
);
=any

some 和any是一样的就不多说了

all

这个all我也没咋用过,all表示所有值,和any有点儿相反的意思

operand comparison_operator ALL (subquery)

> all ():表示大于所有值,即>子查询中最大值
< all() : 表示小于所有值,即< 子查询中的最小值
= all(): 返回单个值时和=一样,返回多个值时貌似没啥用
<> all(): 和not in 一样

select *from t_student 
where s_id > all(
    select s_id from t_student where s_id in (105,109)
);

>all

标量子查询

这种情况下,子查询返回单个值,可以在任何地方使用它。

select
    c_id,
    c_name,
    (select max(s_id) from t_student) as max_s_id
from 
    t_class;


select
    *
from 
    t_class 
where 
    c_id = (select max(c_id) from t_class);

行子查询

上面我们介绍的子查询,都是返回1列多行,行子查询的话,是返回1行多列

-- 查询一班所有男生
select *from t_student
where (c_id,s_gender) = (901,0);
行子查询

这里也可以返回多行多列(也叫做表子查询)

select *from t_student
where (c_id,s_gender) in (select 901,0 union select 902,0);
多行多列

参考资料

官方文档:
https://dev.mysql.com/doc/refman/5.7/en/subqueries.html

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、创建练习使用的数据表 goods_id —— 商品编号goods_name —— 商品名称goods_cate...
    黒猫阅读 4,652评论 0 4
  • 数据准备 回顾 记录操作:写操作:INSERT,UPDATE,DELETE读取操作:SELECT 这章主要学习:子...
    齐天大圣李圣杰阅读 4,709评论 0 4
  • 1、MySQL启动和关闭(安装及配置请参照百度经验,这里不再记录。MySQL默认端口号:3306;默认数据类型格式...
    强壮de西兰花阅读 3,957评论 0 1
  • 一、子查询定义 定义: 子查询允许把一个查询嵌套在另一个查询当中。 子查询,又叫内部查询,相对于内部查询,包含内部...
    我是强强阅读 8,469评论 0 4
  • 我在适当安慰自己调整心态! 不知道从何时练就了这么一招安慰,一直所求的"安全感"早已不远千里。在妈妈的认知里每...
    邓珊珊珊阅读 3,273评论 1 0

友情链接更多精彩内容