Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is assuming that each user can only be joined <em>once</em> to a conversation:</p> <pre><code>SELECT c.* FROM conversations c JOIN notifications n1 ON n1.conversation_id = c.id JOIN notifications n2 ON n2.conversation_id = c.id WHERE n1.user_id = 1 AND n2.user_id = 2 AND NOT EXISTS ( SELECT 1 FROM notifications n3 WHERE n3.conversation_id = c.id AND n3.user_id &lt;&gt; ALL ('{1,2}') ) </code></pre> <p>This is a special case of relational division. We have assembled a whole arsenal of techniques under this this related question:<br> <a href="https://stackoverflow.com/questions/7364969/how-to-filter-sql-results-in-a-has-many-through-relation">How to filter SQL results in a has-many-through relation</a></p> <p>The special requirement is to exclude additional matches. I use <code>NOT EXISTS</code> for this end. You could also use <code>LEFT JOIN / IS NULL</code> or <code>NOT IN</code>. More details here:<br> <a href="https://stackoverflow.com/questions/19363481/select-rows-which-are-not-present-in-other-table/19364694#19364694">Select rows which are not present in other table</a></p> <h3>There could be several notifications for the same user</h3> <p>To avoid duplicate conversations in the result you can use <code>DISTINCT</code> or <code>GROUP BY</code> in addition to the above. Or you suppress duplicates to begin with (probably faster):</p> <pre><code>SELECT c.* FROM conversations c WHERE EXISTS ( SELECT 1 FROM notifications n1 JOIN notifications n2 USING (conversation_id) WHERE n1.conversation_id = c.id AND n1.user_id = 1 AND n2.user_id = 2 ) AND NOT EXISTS ( SELECT 1 FROM notifications n3 WHERE n3.conversation_id = c.id AND n3.user_id &lt;&gt; ALL ('{1,2}') ) </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.
    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.
 

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