简体   繁体   中英

MySQL: what is the most efficient way to retrieve all permissions from RBAC database?

Good day.

I have a role-based access control database and looking for an efficient way to get all permissions user has. This is the schematics:

RBAC数据库设计

Now I need to get all user's permission in the most (possibly) efficient way. Tried this query:

SELECT p.name
  FROM permission p
  WHERE p.id = (
    SELECT rpl.permission_id
    FROM role_permission_list rpl
    WHERE rpl.role_id = (
      SELECT url.role_id
      FROM user_role_list url
      WHERE url.user_id = 2
    )
)

But this fails. Since sub-query returns more than 1 result. Tried to think of a join — couldn't figure it out.

Thanks in advance.

PS: In future there will be an permission_overrides table, since one standalone access-controlled entity may have exclusive set of permissions.

Give this a try:

SELECT u.id, p.name
FROM `user` u
LEFT JOIN user_role_list url ON u.id = url.user_id
LEFT JOIN role r ON r.ID = url.role_id
LEFT JOIN role_permission_list rpl ON rpl.role_id = r.id
LEFT JOIN permission p ON p.ID = rpl.permission_id
WHERE u.id = A_Users_ID

It will be simple 3 joins, like:

SELECT
  `user`.id,
  permission.*
FROM
  `user`
    LEFT JOIN user_role_list ON `user`.id=user_role_list.user_id
    LEFT JOIN role_permission_list ON user_role_list.role_id=role_permission_list.role_id
    LEFT JOIN permission ON role_permission_list.permission_id=permission.id
WHERE
  `user`.id=$user_id

(since you're not looking for role description from which specific permission came, I've not include that table to query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM