SQL Server从表中选择主键在另一个表

时间:2017-01-24 12:07:58

标签: sql sql-server

我有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);

非常感谢指导一名笨蛋学生。

1 个答案:

答案 0 :(得分:3)

您的问题可以通过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