SELECT cat_id
FROM (
SELECT DISTINCT cat_id
FROM cat_product
) cpo
WHERE EXISTS
(
SELECT NULL
FROM cat_product cpi
WHERE cpi.cat_id = cpo.cat_id
AND product_id IN (2, 3)
LIMIT 1, 1
)
Sie müssen einen UNIQUE haben Index auf (cat_id, product_id) (in dieser Reihenfolge), damit dies schnell funktioniert.
Diese Lösung verwendet INDEX FOR GROUP BY um eine Liste unterschiedlicher Kategorien zu erhalten, und EXISTS Prädikat wird etwas schneller sein als COUNT(*) (da die Aggregation etwas Overhead erfordert).
Wenn Sie nach mehr als zwei Produkten suchen müssen, passen Sie das erste Argument auf LIMIT an entsprechend.
Es sollte LIMIT n - 1, 1 sein , wobei n ist die Anzahl der Elemente im IN Liste.
Aktualisierung:
Um die Kategorien zurückzugeben, die alle Produkte aus der Liste und nichts anderes enthalten, verwenden Sie Folgendes:
SELECT cat_id
FROM (
SELECT DISTINCT cat_id
FROM cat_product
) cpo
WHERE EXISTS
(
SELECT NULL
FROM cat_product cpi
WHERE cpi.cat_id = cpo.cat_id
AND product_id IN (2, 3)
LIMIT 1, 1
)
AND NOT EXISTS
(
SELECT NULL
FROM cat_product cpi
WHERE cpi.cat_id = cpo.cat_id
AND product_id NOT IN (2, 3)
)