GRANT <role>

GRANT <role> 语句用于将之前创建的角色授予给现有用户。用户可以通过 SET ROLE <rolename> 语句拥有角色权限,或者通过 SET ROLE ALL 语句拥有被授予的所有角色。

语法图

  1. GrantRoleStmt ::=
  2. 'GRANT' RolenameList 'TO' UsernameList
  3. RolenameList ::=
  4. Rolename ( ',' Rolename )*
  5. UsernameList ::=
  6. Username ( ',' Username )*

示例

创建新角色 analyticsteam 和新用户 jennifer

  1. $ mysql -uroot
  2. CREATE ROLE analyticsteam;
  3. Query OK, 0 rows affected (0.02 sec)
  4. GRANT SELECT ON test.* TO analyticsteam;
  5. Query OK, 0 rows affected (0.02 sec)
  6. CREATE USER jennifer;
  7. Query OK, 0 rows affected (0.01 sec)
  8. GRANT analyticsteam TO jennifer;
  9. Query OK, 0 rows affected (0.01 sec)

需要注意的是,默认情况下,用户 jennifer 需要执行 SET ROLE analyticsteam 语句才能使用与角色相关联的权限:

  1. $ mysql -ujennifer
  2. SHOW GRANTS;
  3. +---------------------------------------------+
  4. | Grants for User |
  5. +---------------------------------------------+
  6. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  7. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  8. +---------------------------------------------+
  9. 2 rows in set (0.00 sec)
  10. SHOW TABLES in test;
  11. ERROR 1044 (42000): Access denied for user 'jennifer'@'%' to database 'test'
  12. SET ROLE analyticsteam;
  13. Query OK, 0 rows affected (0.00 sec)
  14. SHOW GRANTS;
  15. +---------------------------------------------+
  16. | Grants for User |
  17. +---------------------------------------------+
  18. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  19. | GRANT Select ON test.* TO 'jennifer'@'%' |
  20. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  21. +---------------------------------------------+
  22. 3 rows in set (0.00 sec)
  23. SHOW TABLES IN test;
  24. +----------------+
  25. | Tables_in_test |
  26. +----------------+
  27. | t1 |
  28. +----------------+
  29. 1 row in set (0.00 sec)

执行 SET DEFAULT ROLE 语句将用户 jennifer 与某一角色相关联,这样该用户无需执行 SET ROLE 语句就能拥有与角色相关联的权限。

  1. $ mysql -uroot
  2. SET DEFAULT ROLE analyticsteam TO jennifer;
  3. Query OK, 0 rows affected (0.02 sec)
  1. $ mysql -ujennifer
  2. SHOW GRANTS;
  3. +---------------------------------------------+
  4. | Grants for User |
  5. +---------------------------------------------+
  6. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  7. | GRANT Select ON test.* TO 'jennifer'@'%' |
  8. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  9. +---------------------------------------------+
  10. 3 rows in set (0.00 sec)
  11. SHOW TABLES IN test;
  12. +----------------+
  13. | Tables_in_test |
  14. +----------------+
  15. | t1 |
  16. +----------------+
  17. 1 row in set (0.00 sec)

MySQL 兼容性

GRANT <role> 语句与 MySQL 8.0 的角色功能完全兼容。如发现任何兼容性差异,请在 GitHub 上提交 issue

另请参阅