简体   繁体   English

Oracle SQL 子查询 - NOT EXISTS 的使用

[英]Oracle SQL Subquery - Usage of NOT EXISTS

I used a query to find a list of Primary Keys.我使用查询来查找主键列表。 One Primary key per each ForiegnKey in a table by using below query.通过使用以下查询,表中的每个 ForiegnKey 有一个主键。

select foreignKey, min(primaryKey)
from t
group by foreignKey;

Let us say this is the result : 1,4,5让我们说这是结果:1,4,5

NOw I have another table - Table B that has list of all Primary keys.现在我有另一个表 - 表 B 包含所有主键的列表。 It has 1,2,3,6,7,8,9它有 1,2,3,6,7,8,9

I want a write a query using the above query So that I get a subset of the original query(above) that does not exist in Table B. I want 4 and 5 back with the new query.我想使用上面的查询编写一个查询,以便我得到表 B 中不存在的原始查询(上面)的子集。我想用新查询返回 4 和 5。

Use a having clause:使用having子句:

select foreignKey, min(primaryKey)
from t
group by foreignKey
having min(primarykey) not in (select pk from b);

You should also be able to express this as not exists :您还应该能够将其表达为not exists

having not exists (select 1
                   from b
                   where b.pk = min(t.primaryKey)
                  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM