Trying to understand NOT EXISTS
better. Can we always replace NOT EXISTS
when we have NOT IN
, even with nested situation?
I found this similar question, it only has one NOT IN
while trying to do with the nested case.
We have two tables, registered and preActivity .
Registered has mId (string), aId (string), quarter (string), year (integer) and preActivity has aId (string), preAId (string) where
> mId is member id,
> aId is the activity Id,
> preAId is the prerequisite activity Id.
If we have this query with nested NOT IN to find out all the members have registered all the required activities(prerequisite) class before for activity (class) swimming at YMCA. Can we convert it with to two nested NOT EXIST?
SELECT DISTINCT r.mid
FROM registered r
WHERE r.mid NOT IN (SELECT r.mid
FROM preActivity p
WHERE p.aid = "swimming" AND
p.preAId NOT IN (SELECT r2.mid
FROM registered r2
WHERE r2.mid = r.mid));
Using the hint for this post, we can convert one of the NOT IN, but the second one taking me hours. Can someone please help with some explanation ?
Here is what I have so far:
SELECT DISTINCT r.mid
FROM registered r
WHERE NOT EXISTS (SELECT r.mid
FROM preActivity p
WHERE p.aid = "swimming" AND
p.preAId NOT IN (SELECT r2.mid # how can we compare p.preAId with some rows selected from r2 Notice we don't have preAid field from resistered table (following the idea from the post?
FROM registered r2
WHERE r2.mid = r.mid));
Or we can't apply the same idea here since it is a two nested case ?