този проблем се нарича Relational Division
SELECT boy_id
FROM boys_chocolates
WHERE chocolate_id IN ('$string')
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = ? -- <<== number of chocolates specified
пример:
SELECT boy_id
FROM boys_chocolates
WHERE chocolate_id IN (1,2,3,4)
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = 4
обаче, ако chocolate_id
е уникален за всеки boy_id
, DISTINCT
ключовата дума не е задължителна.
SELECT boy_id
FROM boys_chocolates
WHERE chocolate_id IN (1,2,3,4)
GROUP BY boy_id
HAVING COUNT(*) = 4
АКТУАЛИЗИРАНЕ 1
...Искам да избера момчета от масата, които иматточно шоколадите, които споменавам. Не повече, не по-малко...
SELECT boy_id
FROM boys_chocolates a
WHERE chocolate_id IN (1,2,3,4) AND
EXISTS
(
SELECT 1
FROM boys_chocolates b
WHERE a.boy_ID = b.boy_ID
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = 4
)
GROUP BY boy_id
HAVING COUNT(*) = 4