我有这样的数据库
id name group
使用这样的数据
1 john A
2 john B
3 charles B
4 peter B
5 rose B
6 charles A
7 justin C
正如您所看到的,可能性是一个ID与一个组或多个组相关联
我需要一个过滤的查询
a)在A组和B组 b)属于A组而不是B组 c)仅在A组
答案 0 :(得分:1)
a. select distinct name from tablename where group = 'A' or group = 'B';
b. select distinct name from tablename where group = 'A' and group <> 'B';
c. select distinct name from tablename where group = 'A' and
group not in (select distinct(t1.group) from tablename t1
where t1.group <> 'A');
答案 1 :(得分:0)
我喜欢使用group by
和having
子句来解决这些问题。第一个问题:
select name
from table
group by name
having sum(group = 'A') > 1 and sum(group = 'B') > 0;
另外两个是:
having sum(group = 'A') > 1 and sum(group = 'B') = 0;
having sum(group = 'A') > 1 and sum(group <> 'A') = 0;