Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

SQL: join efficiente dove esistono tutti i valori

Il modo più semplice è usare GROUP BY e HAVING:

SELECT group_name
FROM table2 g
JOIN table1 t ON g.group_id = t.group_id
WHERE t.item IN (765, 656)
GROUP BY group_name
HAVING COUNT(DISTINCT t.item) = 2;

Così selezioni solo i gruppi che contengono tutti gli item richiesti.