【问题标题】:Oracle Not exists inside not existsoracle不存在里面不存在
【发布时间】:2014-02-27 11:55:51
【问题描述】:

当我运行这个查询时,伙计们:

SELECT * FROM big_table big
WHERE sum_number = 1
 AND NOT EXISTS ( SELECT 1
                  FROM smal_table smal
                  WHERE other_number = big.other_number
                )

我得到 4 个结果,但是当我运行这个时

SELECT * FROM big_table big
WHERE sum_number = 1
 AND NOT EXISTS ( SELECT 1
                  FROM smal_table smal
                  WHERE other_number = big.other_number
                  AND NOT EXISTS ( SELECT 1
                                    FROM and_another_table another
                                    WHERE and_another_number = big.and_another_number
                                 )
                )

我从 big_table 获取所有行。 有谁知道为什么会发生这种情况? 我想做一个查询,显示 big_table 中不存在于 smal_table 中的所有行,但如果它存在于小表中,我只想要 and_another_table 中不存在的行 谁能帮帮我?

编辑:我想要 big_table 中不在 small_table 中的行加上 big_table 中在 small_table 但不在 and_another_table 中的行

【问题讨论】:

  • 第一个内部选择有很多匹配项,因此您只能获得该集中没有匹配项的 4 条记录。第二个内部选择还有一个条件要满足,所以它找到的记录更少,所以这次大表中当然有更多的记录没有匹配。请再次说明您要选择的内容。我不明白你的解释。

标签: sql oracle not-exists


【解决方案1】:

我认为逻辑是您希望大表中的行不在小表或另一个表中。如果是这样,这应该做你想要的:

SELECT *
FROM big_table big
WHERE sum_number = 1 AND
      (NOT EXISTS (SELECT 1
                   FROM small_table smal
                   WHERE other_number = big.other_number
                  ) OR
       NOT EXISTS (SELECT 1
                   FROM and_another_table another
                   WHERE and_another_number = big.and_another_number
                  )
      );

编辑:

根据下面的评论,where 子句将是:

WHERE sum_number = 1 AND
      (NOT EXISTS (SELECT 1
                   FROM small_table smal
                   WHERE other_number = big.other_number
                  ) OR
       EXISTS (SELECT 1
               FROM and_another_table another
               WHERE and_another_number = big.and_another_number
              )
      );

【讨论】:

  • 不,我想要 big_table 中不在 small_table 中的行加上 big_table 中在 small_table 但不在 and_another_table 中的行
  • @user3360301 。 . .问题是“如果它存在于小表中,我只想要不在 and_another_table 中的行”。我至少对正确的逻辑感到困惑。但是,根据您的评论,您可以将最后一个 not exists 更改为 exists
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2018-04-17
  • 1970-01-01
  • 2021-05-03
  • 2014-11-18
  • 1970-01-01
相关资源
最近更新 更多