SQL INNER JOIN + SELECT NOT EXIST ID's

时间:2018-03-21 16:30:39

标签: sql sql-server mssql-jdbc

我有三张桌子:

表一:用户

表二:角色

表三:UserInRoles

  • 用户
UserID                                |  FullName
--------------------------------------------------
07DCEE4A-6598-42E1-95C6-0390FF8BB534  | John Doe
  • 角色
RoleID
---------------------------------------
E5C46F8E-EE6A-4052-AABA-08184E5F0158
  • UserInRoles
UserID                               | RoleID
---------------------------------------------------------------------------
07DCEE4A-6598-42E1-95C6-0390FF8BB534 | E5C46F8E-EE6A-4052-AABA-08184E5F0158

我需要从表UsersID中选择不在表UserInRoles中的所有Users

我试过:

SELECT DISTINCT Users.UserId, Users.FullName 
FROM Users 
INNER JOIN UserInRoles 
ON Users.UserId <> UserInRoles.UserId

2 个答案:

答案 0 :(得分:4)

思考NOT INNOT EXISTS

select u.*
from users u
where not exists (select 1 from UserInRules ur where u.UserId = ur.UserId);

答案 1 :(得分:0)

要从表Users中选择不在表UserInRoles中的所有UsersID,只需使用not in

select distinct * from users where userid not in
(select userid from UserInroles)