数据库exists

天大地大妈咪最大 提交于 2019-12-03 01:52:37

  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的语法通常会查询索引

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!