[英]SQL Statement Question - How to retrieve records of a table where the primary key does not exist in another table as a foreign key
[英]SQL Server Select from table where primary key does not appear as foreign key in another table
我有3张桌子 -
User UserID PK
SecurityGroup SecurityGroupID PK, SecurityGroupName
UserSecurityGroup UserSecurityGroupID, UserID FK, SecurityGroupID FK
我试图选择用户不属于的安全组的名称。
用户可以是多个组的成员。
即我有三个安全组:管理员,主持人,会员
我通过了一个UserID。 所述用户被分配给Admin和Moderator组,但不属于Member组。 我正在尝试显示“会员”。
这些是我到目前为止的尝试:
尝试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);
尝试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);
对于一个不高兴的学生的指导将非常感激。
您的问题可以通过not exists
查询来回答。 这是一种方法:
select sg.SecurityGroupName
from tblSecurityGroup sg
where not exists (select 1
from tblUserSecurityGroup usg
where sg.SecurityGroupID = usg.SecurityGroupID and
usg.UserID = 1
);
请注意,不需要tblUser
,因为UserID
位于tblUserSecurityGroup
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.