Berikut ini adalah pendekatan performan, tanpa menggunakan subquery sama sekali. Anda cukup memfilter hasil di Having
klausa, menggunakan agregasi bersyarat:
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(*)
Hasil
| conversation_id |
| --------------- |
| 10 |
Variasi lain dari agregasi bersyarat yang mungkin adalah:
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))