I have a table like below:
tbl:
| id | device_id | device_model |
|---|---|---|
| 1 | 101 | A |
| 1 | 201 | B |
| 1 | 202 | B |
| 2 | 102 | A |
| 2 | 301 | C |
| 3 | 103 | A |
| 3 | 203 | B |
| 3 | 302 | C |
I want to select group of ids with specific device_models given with a list.
At first, I tried:
SELECT id
FROM tbl
WHERE device_model IN ('A', 'B')
GROUP BY id
But this works like OR, if an id has only one of ('A', 'B'), then it is returned. This is not the behaviour I want, instead I want an AND behaviour.
Then, I thought I can use this:
SELECT id
FROM tbl
WHERE device_model IN ('A', 'B')
HAVING COUNT(DISTINCT device_model) = 2;
But, this returns ids 1 and 3, but I only want 1 because group with id == 3 also has device_model C.
What can I do to get ids that has only ALL given device_models using a list?
>Solution :
Add the GROUP BY clause and one more condition inside the HAVING clause, that checks the presence of only A,B inside the field device_model.
SELECT id
FROM tbl
GROUP BY id
HAVING COUNT(DISTINCT device_model) = 2
AND MIN(device_model IN ('A', 'B')) = 1;
This should work on MySQL, and should generalize well on any n amount of elements you want to check. It would suffice to add all your elements inside the array, and update the number of distinct elements.
Output:
| id |
|---|
| 1 |
Check the demo here.