February 25, 2009 at 6:28 pm
Hi Every one,
I would apprecriate helping me out on a query that will result in one to one related IDs from a many to many realated data table.
I have a table UserRole(UserID,RoleID) that has the data like this
UserID RoleID
11
45
35
22
23
34
I want to list the IDs that has only one to one relationship, for example in this case I should filter out all users that has many roles and all roles that are associated with many users. so that the query results should be 1,1
I hope I make some sense. Please let me know.
Thanks..
rb
February 25, 2009 at 6:48 pm
i think it should be fairly simple, right? didn't test it, but this is my first guess:
SELECT
UserRole.UserID,
UserRole.RoleID
FROM UserRole
LEFT OUTER JOIN (SELECT UserId, COUNT(RoleID) AS CNT
FROM UserRole
GROUP BY UserID) MYALIAS ON UserRole.UserId = MYALIAS.UserID
WHERE MYALIAS.CNT =1
Lowell
February 25, 2009 at 6:56 pm
Hi Lowel,
Thanks for the quick response.
I think you are very close,
You query resulting two recods
11
45
Role 5 is associated to user 4 so it should be eliminated
Any Idea?
rb
February 25, 2009 at 7:02 pm
I think I figured out from your hint
Following modification is working
Please let me know if I am wrong --thanks
SELECT
UserRole.UserID,
UserRole.RoleID
FROM UserRole
LEFT OUTER JOIN (SELECT UserId, COUNT(RoleID) AS CNT
FROM UserRole
GROUP BY UserID) MYALIAS ON UserRole.UserId = MYALIAS.UserID
LEFT JOIN (SELECT RoleID, COUNT(UserId) AS CNT2
FROM UserRole
GROUP BY RoleID) MYALIAS2 ON UserRole.RoleID = MYALIAS2.RoleID
WHERE MYALIAS.CNT =1
AND MYALIAS2.CNT2 =1
rb
February 25, 2009 at 7:48 pm
yep i think you got it;
do you also need to find users with zero roles, or roles with zero users?
Lowell
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply