[英]MySQL How get record who have exactly label 1 and label 2
我有桌子:
ID Name label
1 Jan 1
2 Jan 2
3 Adam 2
4 Adam 10
5 Kasia 1
我只想获取带有标签1和标签2的记录
例如:
1 Jan
我有很多标签,所以subselect中的subselect中的subselect是个坏主意吗?
您可以通过多种方式执行此操作。 我的首选方法是group by
并having
:
select min(id), name
from table
group by name
having sum(case when label = 1 then 1 else 0 end) > 0 and
sum(case when label = 2 then 1 else 0 end) > 0 ;
对于每个名称,它计算出现“ 1”和出现“ 2”的次数。 > 0
确保每个至少出现一次。
另一种方法是使用intersect
运算符。
select id, name
from tablename where label = 1
intersect
select id, name
from tablename where label = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.