带有用户,角色和权限的SQL SELECT语句

时间:2013-03-05 10:15:01

标签: sql sql-server select

让我们说我有桌子:

  1. 用户
  2. Users_in_Roles
  3. 角色
  4. Rights_in_Roles
  5. 版权
  6. 密钥是标准密钥(UserFk,RoleFk,RightFk)

    问题是:如何让所有具有正确X(id = 100)的角色的用户

    我不知道如何触摸这个问题。请帮助和抱歉我的英语。

    SELECT [dbo].[System_Users].[Id]
      ,[UserName]
      ,[FirstName]
      ,[LastName]
      ,[Email]
      ,RoleFk
      ,[dbo].[System_Roles].Name
      FROM [dbo].[System_Users]
    INNER JOIN [dbo].[System_Roles_System_Users]
    ON [dbo].[System_Roles_System_Users].UserFk = [dbo].[System_Users].Id
    INNER JOIN [dbo].[System_Roles]
    ON [dbo].[System_Roles].Id = [dbo].[System_Roles_System_Users].RoleFk
    
    WHERE ?
    

    我试着这样,你能告诉我我的错吗?

    SELECT 
    DISTINCT System_Users.Id,
    System_Users.FullName
    FROM System_Users
    INNER JOIN Dict_Rights_System_Users
    ON System_Users.Id = Dict_Rights_System_Users.UserFk
    INNER JOIN System_Roles_System_Users
    ON System_Roles_System_Users.UserFk = System_Users.Id
    WHERE
    RightFk = 136
    OR
    136 IN (SELECT Dict_Rights_System_Roles.RightFk FROM Dict_Rights_System_Roles WHERE             
    Dict_Rights_System_Roles.RoleFk = System_Roles_System_Users.RoleFk)
    ORDER BY System_Users.FullName ASC
    

2 个答案:

答案 0 :(得分:2)

您需要JOIN关键关系表。基本结构将是:

select u.Id, 
  u.UserName,
  u.FirstName,
  u.LastName,
  u.Email,
  r.RoleFk,
  r.Name RoleName,
  rt.Name RightName
from users u
inner join users_in_roles ur
  on u.id = ur.userfk
inner join roles r
  on ur.rolefk = r.id
inner join rights_in_roles rr
  on r.rolefk = rr.rolefk
inner join rights rt
  on rr.rightfk = rt.id
where rt.id = 100

如果您需要帮助,请在此处学习JOIN语法,这是一个很好的参考:

答案 1 :(得分:2)

你可以试试这个:

SELECT  *
FROM    Users u
WHERE   EXISTS (
        SELECT  ur.RoleFk
        FROM    Users_in_Roles ur
        WHERE   u.UserPk = ur.UserFk
        AND     EXISTS
                (
                    SELECT  1
                    FROM    Rights_in_Roles rr
                    WHERE   rr.RoleFk = ur.RoleFk
                    AND     rr.RightFk = 100
                )
)
OR  EXISTS (

        SELECT  1
        FROM    Users_Rights uri
        WHERE   u.UserPk = uri.UserFk 
        AND     uri.RightFk = 100
)

请注意,上述查询不会为该角色返回RoleFkName

另一种方法是:

SELECT   u.Id
        ,u.UserName
        ,u.FirstName
        ,u.LastName
        ,u.Email
        ,rr.RoleFk
        ,r.Name
FROM    Users u

        -- get users that are in role that has right
LEFT JOIN   
        Users_in_Roles ur ON
        ur.UserFk = u.UserPk
LEFT JOIN   
        Rights_in_Roles rr ON
        rr.RoleFk = ur.RoleFk
AND     rr.RightFk = 100
LEFT JOIN   
        Rights r ON
        r.RolePk = rr.RoleFk

        -- get users that have a right granted to them directly
LEFT JOIN
        Users_Rights uri ON
        u.UserPk = uri.UserFk 
AND     uri.RightFk = 100

WHERE   rr.RoleFk IS NOT NULL OR uri.UserFk IS NOT NULL