经典权限系统设计(五张表)
大致用到5张表:用户表(UserInfo)、角色表(RoleInfo)、菜单表(MenuInfo)、用户角色表(UserRole)、角色菜单表(RoleMenu)。
各表的大体表结构如下:
1、用户表(UserInfo):Id、UserName、UserPwd
2、角色表(RoleInfo):Id、RoleName
3、菜单表(MenuInfo):Id、MenuName
4、用户角色表(UserRole):Id、UserId、RoleId
5、角色菜单表(RoleMenu):Id、RoleId、MenuId
最关键的地方是,某个用户登录时,如何查找该用户的菜单权限?其实一条语句即可搞定:
假如用户的用户名为zhangsan,则他的菜单权限查询如下:
Select m.Id,m.MenuName from MenuInfo m ,UserInfo u UserRole ur, RoleMenu rm Where m.Id = rm.MenuId and ur.RoleId = rm.RoleId and ur.UserId = u.Id and u.UserName = 'zhangsan'
权限管理系统经典的五张表
DESC t_user
DESC t_role
DESC t_menu
DESC t_userrole
DROP TABLE IF EXISTS t_user;
DROP TABLE IF EXISTS t_role;
DROP TABLE IF EXISTS t_menu;
DROP TABLE IF EXISTS t_userrole;
CREATE TABLE t_user(
usr_id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'ID',
usr_account VARCHAR(32) NOT NULL UNIQUE COMMENT '账号',
usr_password CHAR(32) NOT NULL COMMENT '密码'
)COMMENT '用户表';
CREATE TABLE t_role(
ro_id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'ID',
ro_name VARCHAR(32) NOT NULL UNIQUE COMMENT '角色名'
)COMMENT '角色表';
CREATE TABLE t_menu(
mu_id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'ID',
mu_name VARCHAR(32) NOT NULL UNIQUE COMMENT '菜名'
)COMMENT '菜单表';
CREATE TABLE t_userrole(
ur_usr_id INT COMMENT '用户ID',
ur_ro_id INT COMMENT '角色ID'
)COMMENT '用户角色表';
CREATE TABLE t_rolemenu(
rm_ro_id INT COMMENT '角色ID',
rm_mu_id INT COMMENT '菜单ID',
PRIMARY KEY(rm_ro_id,rm_mu_id),
FOREIGN KEY(rm_ro_id) REFERENCES t_role(ro_id),
FOREIGN KEY(rm_mu_id) REFERENCES t_menu(mu_id)
)COMMENT '角色菜单表';
INSERT INTO t_user(usr_account,usr_password) VALUES('chenxueli','111'); -- SYS
INSERT INTO t_user(usr_account,usr_password) VALUES('chensheng','222'); -- SYSTEM
INSERT INTO t_user(usr_account,usr_password) VALUES('zsf','333'); -- ADMIN
INSERT INTO t_user(usr_account,usr_password) VALUES('zs','444'); -- USER
INSERT INTO t_role(ro_name) VALUES('SYS');
INSERT INTO t_role(ro_name) VALUES('SYSTEM');
INSERT INTO t_role(ro_name) VALUES('ADMIN');
INSERT INTO t_role(ro_name) VALUES('USER');
INSERT INTO t_menu(mu_name) VALUES('拉黑用户');-- SYS
INSERT INTO t_menu(mu_name) VALUES('运费险');-- SYS SYSTEM
INSERT INTO t_menu(mu_name) VALUES('上架');-- SYS SYSTEM ADMIN
INSERT INTO t_menu(mu_name) VALUES('下架');-- SYS SYSTEM ADMIN
INSERT INTO t_menu(mu_name) VALUES('下单');-- USER
INSERT INTO t_menu(mu_name) VALUES('付款');-- USER
INSERT INTO t_userrole VALUES(1,1),(1,2);
INSERT INTO t_userrole VALUES(2,2);
INSERT INTO t_userrole VALUES(3,3);
INSERT INTO t_userrole VALUES(4,4);
INSERT INTO t_rolemenu VALUES(1,1),(1,2);
INSERT INTO t_rolemenu VALUES(2,2),(2,3)(2,4);
INSERT INTO t_rolemenu VALUES(3,3),(3,4);
INSERT INTO t_rolemenu VALUES(4,5),(4,6);
SELECT * FROM t_rolemenu ORDER BY ro_id;