Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL query to find matches for multiple criteria
    primarykey
    data
    text
    <p>If I had a <code>PERMISSIONS</code> table that looked like this:</p> <pre><code>PERSON PERMISSION ------ ---------- Bob red John red John blue Mary red Mary blue Mary yellow </code></pre> <p>and a THINGS table that looks like this:</p> <pre><code>THING PERMISSION ----- ---------- apple red eggplant red eggplant blue </code></pre> <p>I'm trying to come up with a pure SQL query that would let me find out what <code>PERSON</code>s have access to what <code>THING</code>s. Basically, I want a query that would look something like:</p> <pre><code>SELECT person FROM ... vague handwaving here ... WHERE thing = 'eggplant' </code></pre> <p>and have it return "John" and "Mary". The key point being the number of permissions necessary for access to the thing is arbitrary.</p> <p>I feel like this should be obvious, but I just can't come up with an elegant solution. Oracle compatible solutions preferred.</p> <p>Edit:</p> <p>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).</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload