首页 > 数据库技术 > 详细

数据库exists

时间:2019-10-31 12:17:41      阅读:61      评论:0      收藏:0      [点我收藏+]

  EXISTS用于检查子查询是否返回结果,该子查询返回结果为:TRUE/FALSE。也就是说,EXISTS会根据子查询结果的行数返回TRUE/FALSE。

exists对于子查询结果为null的也视为TRUE。前面已经说过EXISTS会根据子查询结果的行数来判断返回TRUE/FALSE。select null 虽然查出来的结果是null但是还是独占行数的,从行数上而言,select null 的结果是true,只是对于exists而言它是这样。

对于EXISTS而言外查询的内容会匹配EXISTS的子查询的内容。

有下面两个表:

FORUM:

技术分享图片

 

 

 

 COMMENT:

技术分享图片

 

 

 可见forum中的数据是一对多于comment中的。

select * from forum f;
/*--等同于   两者都是查询出forum表中的所有数据-*/
select * from forum f where exists(select * from comment );

再看如下:

select * from forum f where exists(
select * from comment c from c.forum_id=f.forum_id
);
/*--等同于-*/
select f.* from forum f where f.forum_id in(
select c.forum_id from comment c where c.forum_id=f.forum_id
);

可见exists在某种程度上是和in是等效的。

值得强调的是,exists对于子查询的结果不甚在意,看如下sql

select * from forum f where exists (
select c.comment_id from comment c where f.author_id=c.responser_id
);
/*-等同于-*/
select * from forum f where f.author_id in (
select c.reponser_id from comment where c.responser_id=f.author_id
);

 

not exists和exists反着来,情况都一样的,需要注意的是:not exists 会比not in快,原因是not exists的语法通常会查询索引

数据库exists

原文:https://www.cnblogs.com/notably/p/11770252.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!