2014-01-14 52 views
-1

假設我有如下表:如何與給定值的選擇行

表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

沒有證據你試過什麼? – hd1

回答

0

構建這樣的查詢的最靈活的方式是使用group byhaving。如果你想這三個特定羣體:

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); 
+0

你的第二個解決方案正是我想要的 – ako

2

您可以使用WHERE,GROUP BYHAVING的組合來獲得結果。 WHERE子句將包含您想要的group_ids的列表。您將在GROUP BY條款適用於您user_id列,最後你將使用HAVING條款,以獲得不同group_ids的計數 - 這個數量應與您在WHERE有ID的數量:

select user_id 
from USERS_GROUPS 
where group_id in (1, 2, 3) 
group by user_id 
having count(distinct group_id) = 3; 

SQL Fiddle with Demo

相關問題