简体   繁体   中英

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.

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

Let us say this is the result : 1,4,5

NOw I have another table - Table B that has list of all Primary keys. It has 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.

Use a having clause:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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