相关子查询如何与Exists运算符一起使用?

时间:2017-03-12 13:37:18

标签: sql oracle subquery

假设我正在使用

select * from emp where Exists (select * from dept)

我从emp表中获取所有记录;

但是当我使用相关子查询执行时,我只获得最小数量的记录

select * from emp e where Exists (select * from dept d where e.eid=d.deptid)

我无法理解它是如何运作的? 那么在哪种情况下我应该将子查询与EXISTS运算符相关联。 任何实时的例子??

2 个答案:

答案 0 :(得分:1)

您可以将相关子查询视为循环(尽管这不一定是它实际运行的方式)。请考虑以下问题:

select e.*
from emp e
where Exists (select 1
              from dept d
              where e.eid = d.deptid
             );

它说:“对于外部查询中的每个emp记录,请检查eid是否匹配dept.deptid。”如果没有匹配项 - 因为e.eidNULL或该值不在dept中,则它不返回任何行。

考虑没有关联子句的查询:

select e.*
from emp e
where Exists (select 1
              from dept d
             );

这是说:“如果emp中存在任何行,则在dept中返回一行。”没有相关子句,因此要么返回所有行,要么都不返回任何行。

答案 1 :(得分:0)

select t1.*
from table1 t1
where exists (
      select 1
      from table2 t2
      where t2.t1_id = t1.id
)

这里发生的是你从table1得到的结果在table2中有匹配的记录。 table2中有多少行与table1中的给定行匹配无关紧要;重要的是,有任何匹配。与内连接不同,你只能为table1中的每一行获得一个结果,在table2中有任意数量的匹配