【问题标题】:Need help in Exists clause with or keyword在 Exists 子句中使用 or 关键字需要帮助
【发布时间】:2021-04-15 01:25:30
【问题描述】:

我正在尝试用 EXISTS 子句更改 IN 子句,但没有得到想要的结果

旧脚本

delete from ABC a 
where column1 IN (select DISTINCT column1 
                  from BCD b 
                  where b.column2 = a.column2 
                      and b.column3 = 'N')
   or a.column3 = "Y";

当我把它改成

delete from ABC a 
where EXISTS (select column1 
              from BCD b 
              where b.column2 = a.column2 
              and b.column3 = 'N')
   or a.column3 = "Y";

我没有得到想要的结果我怀疑这是由于最后使用的 "or" 条件。 需要帮助来解决这个问题。

【问题讨论】:

    标签: sql exists


    【解决方案1】:

    问题不是由 OR 条件引起的。 您的 OLD 脚本正在针对 COLUMN1 验证值

    where column1 IN (select DISTINCT column1 from BCD b where b.column2=a.column2 and b.column3= 'N')
    

    但是,另一个脚本会检查子查询中是否存在任何记录。

    where EXISTS (select column1 from BCD b where b.column2=a.column2 and b.column3= 'N')
    

    总而言之,使用 IN 的查询验证列 1 中是否存在返回值,而 EXISTS 仅检查子查询是否返回 0 行或更多行。

    【讨论】:

    • 嗨 Prateek 感谢您的澄清。请您帮我重写存在,因为 in 子句需要更多时间才能完成
    • 你能给我解释一下这个场景吗?你想达到什么目的?这两个表是如何关联的?
    【解决方案2】:

    您错过了column1 过滤器。请记住,exists 子查询中的投影列没有做任何事情 - 您只是检查子查询是否返回行,而不是它们是什么。我通常使用select null in (not) exists 来让读者明白这一点

    delete from ABC a 
    where EXISTS
     (select null 
      from BCD b 
      where b.column2=a.column2 
      And b.column1 = a.column1
      and b.column3= 'N')
    or a.column3= "Y";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 2017-08-30
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多