If I had a PERMISSIONS
table that looked like this:
PERSON PERMISSION
------ ----------
Bob red
John red
John blue
Mary red
Mary blue
Mary yellow
and a THINGS table that looks like this:
THING PERMISSION
----- ----------
apple red
eggplant red
eggplant blue
I'm trying to come up with a pure SQL query that would let me find out what PERSON
s have access to what THING
s. Basically, I want a query that would look something like:
SELECT person
FROM ... vague handwaving here ...
WHERE thing = 'eggplant'
and have it return "John" and "Mary". The key point being the number of permissions necessary for access to the thing is arbitrary.
I feel like this should be obvious, but I just can't come up with an elegant solution. Oracle compatible solutions preferred.
Edit:
Solutions from Kosta and JBrooks work well. Below is a modified version of Kosta's solution that only hits the indexes twice, as opposed to 3x for Kosta's and 4x for JBrooks's (though I agree with JBrooks that this is probably unnecessary optimization).
SELECT p.person, num_permission, COUNT(p.person)
FROM permissions p
INNER JOIN (
SELECT permission,
COUNT(1) OVER (PARTITION BY thing) AS num_permission
FROM things
WHERE thing = 'eggplant'
) t ON t.permission = p.permission
GROUP BY p.person, num_permission
HAVING COUNT(p.person) = num_permission