选择在其他表中没有关系的记录

时间:2017-10-06 10:16:58

标签: sql oracle

我有以下表格:

enter image description here

其中每个表的主键是其名称+ id(例如:UserRole.UserRoleIdUserRoleUserRole.RoleId的主键和Role的外键在UserRole)。

所以我想选择没有Funcionality的所有Profil(Funcionality.ProfileFuncionality.Count = 0),我用以下查询做了:

SELECT * FROM Funcionality WHERE FuncionalityId NOT IN (SELECT FuncionalityId FROM ProfileFuncionality);

但我无法弄清楚如何进行以下选择:

所有Funcionality没有Role

Funcionality.ProfileFuncionality.Count > 0 
AND Funcionality.ProfileFuncionality.Profile.RoleProfile.Count = 0

所有Funcionality没有User

Funcionality.ProfileFuncionality.Count > 0 
AND Funcionality.ProfileFuncionality.Profile. RoleProfile.Count > 0
AND Funcionality.ProfileFuncionality.Profile.RoleProfile.Role.UserRole.Count = 0

1 个答案:

答案 0 :(得分:1)

只需展开您的子选择:

对于没有角色的所有功能

SELECT *
FROM Funcionality
WHERE FuncionalityId NOT IN
   (SELECT FuncionalityId
    FROM ProfileFuncionality
    JOIN Profile 
        ON Profile.Profileid = ProfileFuncionality.Profileid
    JOIN RoleProfile 
        ON Profile.Profileid = RoleProfile.Profileid);

没有用户的所有功能:

SELECT *
FROM Funcionality
WHERE FuncionalityId NOT IN
    (SELECT FuncionalityId
     FROM ProfileFuncionality
     JOIN Profile 
        ON Profile.Profileid = ProfileFuncionality.Profileid
     JOIN RoleProfile 
        ON Profile.Profileid = RoleProfile.Profileid
     JOIN Role 
        ON Role.Roleid = RoleProfile.Roleid
     JOIN UserRole 
        ON Role.Roleid = UserRole.Roleid)
 MINUS
 SELECT *
 FROM Funcionality WHERE FuncionalityId NOT IN
     (SELECT FuncionalityId
      FROM ProfileFuncionality
      JOIN Profile 
         ON Profile.Profileid = ProfileFuncionality.Profileid
      JOIN RoleProfile 
         ON Profile.Profileid = RoleProfile.Profileid);

我使用减号来减去没有角色出现的功能,因为它们显然也没有用户