mysql in any all_详解mysql子查询(in,not in,any,!=any,all,!=all,some)等实例

在工作和学习中,我们经常使用到mysql子查询in,not in还有不常用的any,!=any,all,!=all,some等。今天刚好整理一下mysql子查询,便于后面查阅。

一、可以按照mysql子查询的类型划分。

6b3a1fe845e491be28a52a3f44a32992.png

1)、按照使用结构。

28cae3de4a981fc5125f22598311ab26.png

where子查询

from子查询

exists子查询

2)、按照返回结果。

5cf4475fa0250ecb35a40bb543eacef7.png

标量子查询

列子查询

行子查询

表子查询

下面我们就按照返回结果的顺序讲解mysql子查询。

1、标量子查询

说明:子查询的返回值是一个标量。

例如:

select * from table where filed = ( select max(filed1) from table1 where filed2 = 'filed2' );

注意:

标量子查询中返回的是一个值,不能有多个值。

这里可以使用 >,=。

2、列子查询

集合运算符

一定要使用集合类的操作符来完成。

in (集合)  | not in(集合)

any(集合) 等于集合中的任何一个即可。等同于in

!=any(集合) 不等于集合中的任意一个。只要与集合中的一些元素,不相等即可。

some 与 any 是同义词。用法语法都是一样的。

all(集合) 集合中的所有元素

!=all(集合) 不等于其中的所有元素,等同于not in。

例如:

select * from table where filed not in ( select id from table1 where filed1 = 'filed1');

select * from table where filed in ( select id from table1 where filed1 = 'filed1');

注意:

这里出来in和not in外,其他的都可以使用 >,=。

3、行子查询

在参与比较时,使用括号可以构建一行。

例如:

select * from table where (filed1,filed2) = (select filed1,filed2 from table2 limit 1);

注意:

1、这里一定要使用limit 1,只能获取到一行记录。否则不能实现行子查询的效果。

2、值得注意的是,where后面的字段和子查询里面的查询的字段要一致,否则不行。

4、表子查询

例如:

select * from (select filed1,filed2,filed3 from table where filed4='filed4') as temp where filed5 = 'filed5';

注意:

如果用于from子查询子句内,from子句内,要求使用一个表,而不能是一个结果。所以应该给这个查询结果起别名。

exists子查询

为什么说它特殊了,因为他的执行流程不同。类似于双重循环。

select * from table where exists ( select * from table1 where table.id=id );

相等于

select * from table where id in ( select id from table1 );

每当查询table表里面的id,就去table1里面全部匹配一遍。

exists与in的区别。

主要区别与解决思路不一样。

ezists:先获得table表里面的每一条记录,然后再去获得table1表里面的记录,找到,则说明符合条件。

in : 先获得table1里面所有的id字段,再去检索table当前id,是否在id的集合内。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值