Please take a look at the question described here: MySQL ONLY IN() equivalent clause , regarding Relational Division in MySQL.
My database structure is very similar to the one described, but in the "Chocolate Boys Table", I have an additional ID field - let's call it milk ID.
Chocolates Boys Table
+----+---------+-----------------------+
| id | chocolate_id | milk id | boy_id |
+----+--------------+---------+--------+
| 1 | 1000 | 2000 | 10007 |
| 2 | 1003 | 2001 | 10007 |
| 3 | 1006 | 2005 | 10007 |
| 4 | 1000 | 2001 | 10009 |
| 5 | 1001 | 2000 | 10009 |
| 6 | 1005 | 2008 | 10009 |
+----+--------------+---------+--------|
The objective is to run a query that retrieves the boy ID that contains the exact chocolate and milk IDs that I pass in. Here are some examples of my expected results:
Example #1:
Chocolate IDs Passed In (in order) - 1000,1003,1006.
Milk IDs Passed In (in order) - 2000,2001,2005.
Expected Result: Query returns boy ID of 10007.
Example #2:
Chocolate IDs Passed In (in order) - 1000,1003.
Milk IDs Passed In (in order) - 2000,2001.
Expected Result: Empty result set.
Example #3:
Chocolate IDs Passed In (in order) - 1003,1000,1006.
Milk IDs Passed In (in order) - 2000,2001,2005.
Expected Result: Empty result set - The passed in IDs are included in boy ID 10007, but the order is wrong. The values of Chocolate ID and Milk ID don't match up if examined on a row by row basis.
I am attempting to use a slightly modified version of John Woo's solution in order to incorporate the added ID field:
SELECT boy_id
FROM boys_chocolates a
WHERE chocolate_id IN (1003,1000,1006) AND milk_id IN (2000,2001,2005) AND
EXISTS
(
SELECT 1
FROM boys_chocolates b
WHERE a.boy_ID = b.boy_ID
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = 3
)
GROUP BY boy_id
HAVING COUNT(*) = 3
The problem that I'm having is that the IN function does not enforce order, as seen in example #3. I would like the above query to return an empty result set. What needs to be changed in order to address this problem? Thank you!