MySQL show grants 的替代 SQL 查询账号权限

SHOW GRANTS 可查询指定账号的权限,如 SHOW GRANTS FOR 'root'
替代的实现 SQL:

SELECT GRANTEE, `GRANTS`
FROM 
(
    SELECT
    	 GRANTEE, CONCAT('GRANT ', GROUP_CONCAT(PRIVILEGE_TYPE SEPARATOR ', '), ' ON ', '*.*', ' TO ', GRANTEE) AS `GRANTS`
    FROM information_schema.USER_PRIVILEGES
    GROUP BY GRANTEE

    UNION ALL 
    
    SELECT
     	 GRANTEE, CONCAT('GRANT ', GROUP_CONCAT(PRIVILEGE_TYPE SEPARATOR ', '), ' ON `', TABLE_SCHEMA, '`.* TO ', GRANTEE) AS `GRANTS`
    FROM information_schema.SCHEMA_PRIVILEGES 
    GROUP BY GRANTEE, TABLE_SCHEMA

    UNION ALL 

    SELECT  
    	 GRANTEE, CONCAT('GRANT ', GROUP_CONCAT(PRIVILEGE_TYPE SEPARATOR ', '), ' ON `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` TO ', GRANTEE) AS `GRANTS`
    FROM information_schema.TABLE_PRIVILEGES 
    -- WHERE TABLE_SCHEMA <> 'mysql' -- 排除 mysql 库
    GROUP BY GRANTEE, TABLE_SCHEMA, TABLE_NAME
) AS t
-- WHERE GRANTEE LIKE "'root'%" -- 筛选 root 用户的权限
ORDER BY GRANTEE, `GRANTS`

输出效果MySQL show grants 的替代 SQL 查询账号权限_第1张图片

你可能感兴趣的:(数据库,mysql,sql,数据库)