要獲得正好包含指定用戶的所有組(即所有指定的用戶和沒有其他用戶)
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
如果你能保證'USER_ID,group_id'是獨一無二的 - 那麼'COUNT' +'GROUP BY '+'HAVING' – zerkms
user_id 2如何屬於組C.我認爲組b是你所需要的? –
是,B組,感謝Dinup –