[英]SQL Server Select from table where primary key does not appear as foreign key in another table
I have 3 tables - 我有3张桌子 -
User UserID PK
SecurityGroup SecurityGroupID PK, SecurityGroupName
UserSecurityGroup UserSecurityGroupID, UserID FK, SecurityGroupID FK
I am trying to select the names of the security groups that a user is NOT a part of. 我试图选择用户不属于的安全组的名称。
A user can be a member of more than one group. 用户可以是多个组的成员。
ie I have three security groups: Admin, Moderator, Member 即我有三个安全组:管理员,主持人,会员
I pass through a UserID. 我通过了一个UserID。 Said user is assigned to the Admin and Moderator groups but is NOT part of the Member group.
所述用户被分配给Admin和Moderator组,但不属于Member组。 I'm trying to display "Member".
我正在尝试显示“会员”。
These are my attempts so far: 这些是我到目前为止的尝试:
Attempt 1 - 尝试1 -
select tblSecurityGroup.SecurityGroupName
from tblSecurityGroup
inner join tblUserSecurityGroup
on tblSecurityGroup.SecurityGroupID = tblUserSecurityGroup.SecurityGroupID
inner join tblUser
on tblUserSecurityGroup.UserID = tblUser.UserID
where tblUser.UserID = 1
and tblSecurityGroup.SecurityGroupID not in (tblUserSecurityGroup.SecurityGroupID);
Attempt 2 - 尝试2 -
select tblSecurityGroup.SecurityGroupName
from tblSecurityGroup
inner join tblUserSecurityGroup
on tblSecurityGroup.SecurityGroupID = tblUserSecurityGroup.SecurityGroupID
inner join tblUser
on tblUserSecurityGroup.UserID = tblUser.UserID
where tblUser.UserID = 1
and not exists (select tblSecurityGroup.SecurityGroupID
from tblSecurityGroup
where tblUserSecurityGroup.SecurityGroupID = tblSecurityGroup.SecurityGroupID);
Guidance for a nooby student would be most appreciated. 对于一个不高兴的学生的指导将非常感激。
Your question can be answered by a not exists
query. 您的问题可以通过
not exists
查询来回答。 Here is one method: 这是一种方法:
select sg.SecurityGroupName
from tblSecurityGroup sg
where not exists (select 1
from tblUserSecurityGroup usg
where sg.SecurityGroupID = usg.SecurityGroupID and
usg.UserID = 1
);
Note that tblUser
is not needed because UserID
is in tblUserSecurityGroup
. 请注意,不需要
tblUser
,因为UserID
位于tblUserSecurityGroup
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.