【问题标题】:How does correlated sub query works with Exists operator?相关子查询如何与 Exists 运算符一起使用?
【发布时间】:2017-03-12 13:37:18
【问题描述】:

假设我在使用时

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 运算符相关联。 有实时的例子吗??

【问题讨论】:

  • 这些是真实的查询吗?您是否缺少where 子句?

标签: sql oracle subquery


【解决方案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
             );

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

【讨论】:

    【解决方案2】:
    select t1.*
    from table1 t1
    where exists (
          select 1
          from table2 t2
          where t2.t1_id = t1.id
    )
    

    这里发生的情况是,您从 table1 获得了在 table2 中具有匹配记录的结果。 table2 中有多少行与 table1 中的给定行匹配无关紧要;重要的是根本没有任何匹配。与内连接不同,对于 table1 中的每一行,在 table2 中有任意数量的匹配项,您只会得到一个结果

    【讨论】:

      猜你喜欢
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多