用户角色权限查询

时间:2011-11-17 13:50:43

标签: sql

我有5个表:用户> user_has_role>角色> role_has_permission>许可

用户可以拥有0或*角色。 角色可以拥有0或*权限

现在我有一个查询,它将获得属于用户的所有权限。 这项工作但现在我希望如果用户具有角色“super_admin”,则所有权限都会加入。但是没有在表role_has_permission中指定它们。

这是查询:

SELECT        p.name,r.name role
FROM          user_has_role AS ur
JOIN          role AS r
ON            ur.role_id = r.id
JOIN          role_has_permission AS rp
ON            r.id = rp.role_id
LEFT JOIN     permission AS p
ON            rp.permission_id = p.id
WHERE         ur.user_id = [USER_ID]

1 个答案:

答案 0 :(得分:1)

你可以做一个工会:

SELECT        p.name,r.name role
FROM          user_has_role AS ur
JOIN          role AS r
ON            ur.role_id = r.id
JOIN          role_has_permission AS rp
ON            r.id = rp.role_id
LEFT JOIN     permission AS p
ON            rp.permission_id = p.id
WHERE         ur.user_id = [USER_ID]
UNION
   SELECT p.name, 'super_admin' 
   FROM permission 
   WHERE EXISTS (SELECT * FROM user_has_role, role 
              WHERE ur.user_id = [USER_ID] and role.role_id = user_has_role.role_id and             
              role.name = 'super_admin')