[英]How to get an exact result of my sql query in a link table
Im trying to get the groups where the brand_id's match exactly to the group.我正在尝试获取brand_id 与该组完全匹配的组。
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.我已经尝试过这个解决方案(见小提琴),但是当我尝试获取一个具有分配给所有组的品牌 ID 的项目时,它会显示所有三个组。 But it should match zero, because its not an exact match.但它应该匹配零,因为它不是完全匹配。
http://sqlfiddle.com/#!9/a5b16e/2/0 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这应该返回第 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这应该只返回 group_id 1
You can do it with sub-query:您可以使用子查询来做到这一点:
select group_id
from mailgroups
where group_id in (select group_id from mailgroups where brand_id = 2)
GROUP BY group_id
HAVING COUNT(brand_id) = 1;
select group_id
from mailgroups
where group_id in (select group_id from mailgroups where brand_id in (1,2))
GROUP BY group_id
HAVING COUNT(brand_id) = 2;
OR with join
:或join
:
select a.group_id
from mailgroups a
left join mailgroups b
on a.id = b.id
and b.brand_id in (1,2)
GROUP BY a.group_id
HAVING COUNT(a.brand_id) = 2;
select a.group_id
from mailgroups a
left join mailgroups b
on a.id = b.id
and b.brand_id in (2)
GROUP BY a.group_id
HAVING COUNT(a.brand_id) = 1;
You don't need subqueries or joins.您不需要子查询或连接。
Set the correct conditions in the having
clause and remove the where
clause:在having
子句中设置正确的条件并删除where
子句:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.