4

ユーザーテーブル

ID | name 
1  | ada    
2  | bob   
3  | tom  

グループテーブル

ID | name
1  | group A
2  | group B
3  | group C

user_group テーブル

user_id | group_id
1       | 1
2       | 1
1       | 2
2       | 2
3       | 2
1       | 3
3       | 3

指定されたユーザー ID のグループ: [1, 2, 3]

上記のリストのすべてのユーザーが属するグループを照会する方法は? (この場合:グループB)

4

4 に答える 4

6

指定されたユーザーを正確に含むすべてのグループを取得するには (つまり、指定されたすべてのユーザーであり、他のユーザーは含まれていません)。

DECLARE @numUsers int = 3

SELECT ug.group_id
       --The Max doesn't really do anything here because all
       --groups with the same group id have the same name.  The
       --max is just used so we can select the group name eventhough
       --we aren't aggregating across group names
     , MAX(g.name) AS name
FROM user_group ug
--Filter to only groups with three users
JOIN (SELECT group_id FROM user_group GROUP BY group_id HAVING COUNT(*) = @numUsers) ug2
  ON ug.group_id = ug2.group_id
JOIN [group] g
    ON ug.group_id = g.ID
WHERE user_id IN (1, 2, 3)
GROUP BY ug.group_id
--The distinct is only necessary if user_group
--isn't keyed by group_id, user_id
HAVING COUNT(DISTINCT user_id) = @numUsers

指定したすべてのユーザーを含むグループを取得するには:

    DECLARE @numUsers int = 3    

    SELECT ug.group_id
           --The Max doesn't really do anything here because all
           --groups with the same group id have the same name.  The
           --max is just used so we can select the group name eventhough
           --we aren't aggregating across group names
         , MAX(g.name) AS name
    FROM user_group ug
    JOIN [group] g
        ON ug.group_id = g.ID
    WHERE user_id IN (1, 2, 3)
    GROUP BY ug.group_id
    --The distinct is only necessary if user_group
    --isn't keyed by group_id, user_id
    HAVING COUNT(DISTINCT user_id) = 3

SQL フィドル: http://sqlfiddle.com/#!6/0e968/3

于 2013-07-22T05:12:43.963 に答える
1

これを試して:

Select t2.name         
     FROM        
    (Select group_id 
       From 
        user_group 
      Group by group_id 
     Having Count(user_id) = (Select Count(*) FROM User_Table)) AS T1        
     INNER JOIN        
       Group_Table AS T2
         ON T1.group_id = T2.ID 

フィドルを参照してください: http://sqlfiddle.com/#!2/fa7250/4

于 2013-07-22T06:11:55.310 に答える
0
SELECT name FROM group_tbl WHERE id IN (SELECT g_id FROM user_grp GROUP BY g_id HAVING Count(u_id)=(SELECT Count(id) FROM user_tbl));
于 2013-07-22T05:48:27.340 に答える
0
Select UserID,count(*)
From UserGroupTable
group by UserID

これにより、UserID/GroupID が一意である 3 のカウントが得られます (zerkms が指摘したように)

于 2013-07-22T05:09:24.463 に答える