如何简化多对多关系之间的查询

时间:2013-10-14 06:38:04

标签: sql sql-server

我想知道如何简化此查询,在这里(http://sqlfiddle.com/#!3/2789c/4)你有完整的例子

SELECT distinct (R.[roleId])
FROM [Role] R
LEFT  JOIN [userRole] U ON R.[roleId] = U.[roleId]
WHERE R.RoleID NOT IN(
  SELECT [roleId] 
  from [dbo].[userRole] 
  WHERE userId = 2) 

我希望获得未分配给特定用户的所有角色。我认为内部选择可能是擦除。

更新1

在您的大力帮助之后,我只能使用一个SELECT http://sqlfiddle.com/#!3/2789c/87

SELECT R.[roleID]
FROM [Role] R
LEFT  JOIN [userRole] U
ON R.[roleID] = U.[roleID] AND U.userId = @userID
WHERE U.userId IS NULL

3 个答案:

答案 0 :(得分:3)

尽可能简单:

select roleId
  from Role
except
select roleId
  from userRole
 where userId = 2

答案 1 :(得分:1)

SELECT R.roleId
FROM [Role] R
LEFT JOIN [userRole] U ON R.roleId = U.roleId
group by r.roleId
having sum(case when U.userId = 2 then 1 else 0 end) = 0

SQLFiddle demo

答案 2 :(得分:1)

你也可以尝试这个

Select distinct role.roleID from role , userrole
except 
select roleId from userrole where userID=2

OR

SELECT R.roleId
FROM [Role] R
LEFT JOIN [userRole] U ON R.roleId = U.roleId
except 
select roleId from userrole where userID=2