Her er en effektiv tilgang, der ikke bruger nogen underforespørgsler overhovedet. Du kan blot filtrere resultater fra i Having
klausul ved hjælp af betinget aggregering:
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(*)
Resultat
| conversation_id |
| --------------- |
| 10 |
En anden mulig variation af betinget aggregering er:
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))