首页 > 代码库 > 连表查询

连表查询

########################## RBAC ################################DROP TABLE IF EXISTS php34_privilege;CREATE TABLE php34_privilege(	id smallint unsigned not null auto_increment,	pri_name varchar(30) not null comment ‘权限名称‘,	module_name varchar(10) not null comment ‘模块名称‘,	controller_name varchar(10) not null comment ‘控制器名称‘,	action_name varchar(10) not null comment ‘方法名称‘,	parent_id smallint unsigned not null default ‘0‘ comment ‘上级权限的ID,0:代表顶级权限‘,	primary key (id))engine=MyISAM default charset=utf8 comment ‘权限表‘;DROP TABLE IF EXISTS php34_role_privilege;CREATE TABLE php34_role_privilege(	pri_id smallint unsigned not null comment ‘权限的ID‘,	role_id smallint unsigned not null comment ‘角色的id‘,	key pri_id(pri_id),	key role_id(role_id))engine=MyISAM default charset=utf8 comment ‘角色权限表‘;DROP TABLE IF EXISTS php34_role;CREATE TABLE php34_role(	id smallint unsigned not null auto_increment,	role_name varchar(30) not null comment ‘角色名称‘,	primary key (id))engine=MyISAM default charset=utf8 comment ‘角色表‘;DROP TABLE IF EXISTS php34_admin_role;CREATE TABLE php34_admin_role(	admin_id tinyint unsigned not null comment ‘管理员的id‘,	role_id smallint unsigned not null comment ‘角色的id‘,	key admin_id(admin_id),	key role_id(role_id))engine=MyISAM default charset=utf8 comment ‘管理员角色表‘;DROP TABLE IF EXISTS php34_admin;CREATE TABLE php34_admin(	id tinyint unsigned not null auto_increment,	username varchar(30) not null comment ‘账号‘,	password char(32) not null comment ‘密码‘,	is_use tinyint unsigned not null default ‘1‘ comment ‘是否启用 1:启用0:禁用‘,	primary key (id))engine=MyISAM default charset=utf8 comment ‘管理员‘;INSERT INTO php34_admin VALUES(1,‘root‘,‘bafcbdc80e0ca50e92abe420f506456b‘,1);# 角色表 role#id    role_name#-------------# 1        a# 2        b# 权限表 privilege#id    pri_name#-------------# 1        a# 2        b# 3        c# a角色拥有bc两个权限#php34_role_privilege#role_id   pri_id#--------------------#   1        2              -->  1这个角色拥有2这个权限#   1        3              -->  1这个角色拥有3这个权限# 有以上五张表之后写SQL取出管理员ID为3的管理员所拥有的所有的权限# 流程:1. 先取出3这个管理员所在的角色ID # SELECT role_id FROM  php34_admin_role WHERE admin_id=3# 2. 再取出这些角色所拥有的权限的ID # SELECT pri_id FROM php34_role_privilege WHERE role_id IN (1上面的结果)# 3. 再根据权限ID取出这些权限的信息# SELECT * FROM php34_privilege WHERE id IN(2的结果)# 最终:# SELECT * FROM php34_privilege WHERE id IN(#	SELECT pri_id FROM php34_role_privilege WHERE role_id IN (#		SELECT role_id FROM  php34_admin_role WHERE admin_id=3#	)# )# 写法二、# SELECT a.*#   FROM php34_privilege a,php34_role_privilege b,php34_admin_role c#    WHERE c.admin_id=3 AND b.pri_id=a.id AND b.role_id=c.role_id# 写法三、# SELECT b.*#  FROM php34_role_privilege a#   LEFT JOIN php34_privilege b ON a.pri_id=b.id#   LEFT JOIN php34_admin_role c ON a.role_id=c.id#    WHERE c.admin_id=3

  

连表查询