2013-07-22 24 views
4

用戶表(SQL)匹配用戶屬於哪個組給定的user_id []

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]

t o查詢上述列表中的所有用戶屬於哪個組? (在這種情況下:B組)

+1

如果你能保證'USER_ID,group_id'是獨一無二的 - 那麼'COUNT' +'GROUP BY '+'HAVING' – zerkms

+0

user_id 2如何屬於組C.我認爲組b是你所需要的? –

+0

是,B組,感謝Dinup –

回答

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

+1

我認爲你不需要加入 – FUD

+0

但是這隻有在zerkms提出的是正確的時纔有效。 – FUD

+0

@FUD'JOIN'只是爲了從OPT表中獲取信息而獲取信息。 –

0
Select UserID,count(*) 
From UserGroupTable 
group by UserID 

這將給3在用戶ID /羣ID是唯一的計數(如zerkms指出)

+1

這不是一個goodsolution如果我只想要[1,2]您的解決方案將返回第1組和第3,這是錯的 – FUD

+0

問題詢問「給user_id []」..所以WHERE子句/或類似的限制查詢的方式是必要的。 –

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

+0

這不是一個通用的解決方案,如果我們想知道組用戶[1,3]都在... –

+0

我還以爲你要檢查所有用戶表中可用的mebers。 – Transformer

+0

對不起,我做到了不清楚 –

相關問題