Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I assume that the natrual key of this table is document_id + subject_id, and that id is a surrogate; IOW, document_id and subject_id are unique. As such, I'm just going to pretend it doesn't exist and that a unique constraint is on the natural key.</p> <p>Let's start with the obvious.</p> <pre><code>SELECT document_id, subject_id FROM document_subjects WHERE subject_id IN (17,76) </code></pre> <p>That gets you everything you want <em>plus</em> stuff you don't want. So all we need to do is filter out the other stuff. The "other stuff" is groups of rows having a count that is not equal to the count of the desired subjects.</p> <pre><code>SELECT document_id FROM document_subjects WHERE subject_id IN (17,76) GROUP BY document_id HAVING COUNT(*) = 2 </code></pre> <p>Note that subject_id is removed because it doesn't participate in grouping. Taking this one step further, i'm going to add an imaginary table called subjects_i_want that contains N rows of subjects you want.</p> <pre><code>SELECT document_id FROM document_subjects WHERE subject_id IN (SELECT subject_id FROM subjects_i_want) GROUP BY document_id HAVING COUNT(*) = (SELECT COUNT(*) FROM subjects_i_want) </code></pre> <p>Obviously subjects_i_want could be swapped out for another subquery, temporary table, or whatever. But, once you have this list of document_id, you can use it within a subselect of a bigger query. </p> <pre><code>SELECT document_id, subject_id, ... FROM document_subjects WHERE document_id IN( SELECT document_id FROM document_subjects WHERE subject_id IN (SELECT subject_id FROM subjects_i_want) GROUP BY document_id HAVING COUNT(*) = (SELECT COUNT(*) FROM subjects_i_want)) </code></pre> <p>Or whatever.</p>
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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