假设我有下表:
表USERS_GROUPS
USER_ID | GROUP_ID
100 1
101 1
101 2
102 1
102 2
102 3
103 1
103 2
103 3
我只需要选择那些拥有所有组(1,2和3)的用户,即
查询结果:
USER_ID
102
103
如何编写这样的SQL查询?
答案 0 :(得分:2)
您可以使用WHERE
,GROUP BY
和HAVING
的组合来获得结果。 WHERE
子句将包含您想要的group_ids
列表。您将GROUP BY
子句应用于user_id
列,最后您将使用HAVING
子句来计算不同的group_ids
- 此计数应与您在WHERE
:
select user_id
from USERS_GROUPS
where group_id in (1, 2, 3)
group by user_id
having count(distinct group_id) = 3;
答案 1 :(得分:1)
构建此类查询的最灵活方式是使用group by
和having
。如果你想要这三个特定群体:
select ug.user_id
from users_groups ug
group by ug.user_id
having sum(case when group_id = 1 then 1 else 0 end) > 0 and
sum(case when group_id = 2 then 1 else 0 end) > 0 and
sum(case when group_id = 3 then 1 else 0 end) > 0 ;
如果您希望表中所有组中的用户:
select ug.user_id
from users_groups ug
group by ug.user_id
having count(distinct ug.group_id) = (select count(distinct group_id) from user_groups);