从5个表中选择。结合两个查询。多对多的关系

时间:2014-01-28 21:40:48

标签: sql sql-server join many-to-many

我有桌子:

  • UsersId, Name, Login, Email
  • RolesId, Name
  • UsersRolesId, UserId, RoleId
  • Permissions:Id, Name
  • RolesPermissionsId, RoleId, PermissionId

如何组合这两个查询:

第一个查询 - 选择所有具有角色的用户:

SELECT  
   Users.Id, 
   (SELECT u.Email 
    FROM Users u 
    WHERE u.Id = Users.Id) AS UserEmail,
   STUFF ((SELECT ', ' + Roles.Name 
           FROM UsersRoles ur2
           LEFT JOIN Roles ON Roles.Id = ur2.RoleId
           LEFT JOIN Users ON Users.Id = ur2.UserId
           WHERE ur1.UserId = ur2.UserId 
           FOR XML path( '' )), 1, 2, '') AS RoleName
FROM UsersRoles ur1
LEFT JOIN Roles ON Roles.Id = ur1.RoleId
LEFT JOIN Users ON Users.Id = ur1.UserId
GROUP BY Users.Id, ur1.UserId

第二个查询 - 选择具有权限的所有角色:

SELECT  
   Roles.Id, 
   (SELECT r.Name 
    FROM Roles r 
    WHERE r.Id = Roles.Id) AS RoleName,
   STUFF ((SELECT ', ' + [Permissions].Name 
           FROM RolesPermissions rp2
           LEFT JOIN [Permissions] ON [Permissions].Id = rp2.PermissionId
           LEFT JOIN Roles ON Roles.Id = rp2.RoleId
           WHERE rp1.RoleId = rp2.RoleId 
           FOR XML path('')), 1, 2, '') AS PermissionName
FROM RolesPermissions rp1
LEFT JOIN [Permissions] ON [Permissions].Id = rp1.PermissionId
LEFT JOIN Roles ON Roles.Id = rp1.RoleId
GROUP BY Roles.Id, rp1.RoleId

如何选择具有权限的所有用户?

STUFF - 将字符串插入另一个字符串。它删除起始位置的目标字符串中指定长度的字符,然后将第二个字符串插入到起始位置的目标字符串中。

1 个答案:

答案 0 :(得分:0)

试试此链接,发布的问题与您的问题极为相似。 Combine two small queries (that group by different values) into one query 让我知道它是否有帮助!