sql中exists和in的语法与区别

2 篇文章 0 订阅
2 篇文章 0 订阅

exists和in的区别很小,几乎可以等价,但是sql优化中往往会注重效率问题,今天咱们就来说说exists和in的区别。
exists语法:
select … from table where exists (子查询)
将主查询的结果,放到子查询结果中进行校验,如子查询有数据,则校验成功,那么符合校验,保留数据。

create table teacher
(
tid int(3),
tname varchar(20),
tcid int(3)
);
insert into teacher values(1,'tz',1);
insert into teacher values(2,'tw',2);
insert into teacher values(3,'tl',3);

例如:

select tname from teacher exists(select * from teacher);

此sql语句等价于select tname from teacher
(主查询数据存在于子查询,则查询成功(校验成功))

select tname from teacher where exists (select * from teacher where tid =9999) ;

此sql返回为空,因为子查询并不存在这样的数据。
in语法:
select … from table where 字段 in (子查询)

select ..from table where tid in  (1,3,5) ;

select * from A where id in (select id from B);
区别:
如果主查询的数据集大,则使用in;
如果子查询的数据集大,则使用exists;
例如:

select tname from teacher where exists (select * from teacher);

这里很明显,子查询查询所有,数据集大,使用exists,效率高。

select * from teacher where tname in (select tname from teacher where tid = 3);

这里很明显,主查询数据集大,使用in,效率高。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻啦猫@_@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值