|
-
Mar 25th, 2009, 11:22 PM
#1
[RESOLVED] Many to Many problem: List the users that belong to all groups
I just don't remember how to do it:
3 Tables:
User: @UserCode, Name
Group: @GroupCode, GroupName
UserGroup: @UserCode, @GroupCode (Associative Table)
- How to list all the Users that belong to all groups?
I just don't remember the correct way to do it, i don't want to do it using Count().
-
Mar 25th, 2009, 11:26 PM
#2
Re: Many to Many problem: List the users that belong to all groups
Simple join:
Code:
SELECT User.UserCode, User.Name, [Group].GroupCode, [Group].GroupName
FROM User
INNER JOIN UserGroup
ON User.UserCode = UserGroup.UserCode
INNER JOIN [Group]
ON [Group].GroupCode = UserGroup.GroupCode
-
Mar 25th, 2009, 11:42 PM
#3
Re: Many to Many problem: List the users that belong to all groups
But what i need is the list of Users that are assigned to all groups, excluding those Users that are assigned to some Groups but not all.
Example:
UserGroup Table:
Name GroupCode
-------- ---------
Juan 1
Juan 3
Pepe 1
Pepe 2
Sonia 1
Sonia 2
Sonia 3
Sonia 4
Group Table:
Code GroupName
---- ------------------
1 Group1
2 Group2
3 Group3
4 Group4
In this Case the Query should only return Sonia, because she is the only user assigned to all groups.
-
Mar 25th, 2009, 11:45 PM
#4
Re: Many to Many problem: List the users that belong to all groups
Oh, I see. I thought it seemed a bit too easy. I'll cogitate on it a bit.
-
Mar 25th, 2009, 11:49 PM
#5
Re: Many to Many problem: List the users that belong to all groups
 Originally Posted by jmcilhinney
Oh, I see. I thought it seemed a bit too easy.  I'll cogitate on it a bit.
no prob , i remember this is an especial case that requieres certain trick i just don't remember, this case is normally used in tests. I remember it was something about getting those users that have some groups assigned but not all, and then doing a NOT IN on the rest of the users, i just can't remember how it was.
-
Mar 26th, 2009, 02:17 AM
#6
Re: Many to Many problem: List the users that belong to all groups
I just found a way to do it, i don't know if it's the best way but it works..
Code:
SELECT User.UserCode, User.Name
FROM User
WHERE NOT EXISTS
(
SELECT 1
FROM Group LEFT JOIN UserGroups
ON Group.GroupCode = UserGroup.GroupCode
AND UserGroup.Name= User.Name
WHERE UserGroup.Name IS NULL
)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|