0

我想知道如何简化这个查询,在这里(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
4

3 回答 3

3

As simple as it gets:

select roleId
  from Role
except
select roleId
  from userRole
 where userId = 2
于 2013-10-14T07:34:14.367 回答
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 演示

于 2013-10-14T06:42:12.677 回答
1

你也可以试试这个

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

或者

SELECT R.roleId
FROM [Role] R
LEFT JOIN [userRole] U ON R.roleId = U.roleId
except 
select roleId from userrole where userID=2
于 2013-10-14T07:40:26.667 回答