How to get an exact result of my sql query in a link table

Ronald McDonald :

Im trying to get the groups where the brand_id's match exactly to the group.

I've tried this solution (see fiddle) but when i try to obtain one item that has a brand id that is assigned to all the groups it shows all three groups. But it should match zero, because its not an exact match.

http://sqlfiddle.com/#!9/a5b16e/2/0

I was wondering if there is a solution to this

SELECT  group_id as groep
FROM    mailgroups a
WHERE   a.brand_id IN (2)
GROUP BY a.group_id
HAVING COUNT(*) = 1

this should return group 3

SELECT  group_id as groep
FROM    mailgroups a
WHERE   a.brand_id IN (2, 1)
GROUP BY a.group_id
HAVING COUNT(*) = 2

and this should only return group_id 1

forpas :

You don't need subqueries or joins.
Set the correct conditions in the having clause and remove the where clause:

SELECT  group_id as groep
FROM    mailgroups 
GROUP BY group_id
HAVING SUM(brand_id IN (2)) = 1 AND SUM(brand_id NOT IN (2)) = 0;

SELECT  group_id as groep
FROM    mailgroups 
GROUP BY group_id
HAVING SUM(brand_id IN (1, 2)) = 2 AND SUM(brand_id NOT IN (1, 2)) = 0;

See the demo.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16554&siteId=1