Ecco un approccio performante, che non utilizza affatto subquery. Puoi semplicemente filtrare i risultati in Having
clausola, utilizzando l'aggregazione condizionale:
SELECT
conversation_id
FROM assoc_user__conversation
GROUP BY conversation_id
HAVING
-- all the rows to exists only for 1000001 or 1000002 only
SUM(user_id IN (1000001, 1000002)) = COUNT(*)
Risultato
| conversation_id |
| --------------- |
| 10 |
Un'altra possibile variazione dell'aggregazione condizionale è:
SELECT
conversation_id
FROM assoc_user__conversation
GROUP BY conversation_id
HAVING
-- atleast one row for 1000001 to exists
SUM(user_id = 1000001) AND
-- atleast one row for 1000002 to exists
SUM(user_id = 1000002) AND
-- no row to exist for other user_id values
NOT SUM(user_id NOT IN (1000001, 1000002))