现在的位置: 首页 > 综合 > 正文

mysql find_in_set用法 以及group_concat()函数

2017年11月02日 ⁄ 综合 ⁄ 共 1092字 ⁄ 字号 评论关闭

      菜鸟自己做php后台权限管理的时候碰到一个问题,连表查询

建表sql

/*********权限表********/
drop table if exists my_privilege;
create table my_privilege(
id mediumint unsigned not null auto_increment comment 'id',
pri_name varchar(30) not null comment '权限名称',
module_name varchar(30) not null comment '模块名',
controller_name varchar(30) not null comment '控制器名',
action_name varchar(30) not null comment '方法名',
parent_id mediumint unsigned not null default '0' comment '上级权限的id',
pri_level tinyint unsigned not null default '0' comment'权限的级别。0:代表第一级:1:代表第二级',
primary key (id)
)engine myisam charset=utf8;
/******角色表******/
drop table if exists my_role;
create table my_role(
id mediumint unsigned not null auto_increment comment 'id',
role_name varchar(30) not null comment '角色名称',
pri_id varchar(150) not null default '' comment '权限id,如果有多个用逗号隔开,如1,2,3',
primary key (id)
)engine myisam charset=utf8 comment'角色';

2表示多对多的关系

一个角色拥有多个权限

一个权限可以被多个权限拥有

角色添加完成过后,显示所拥有的权限显示的是权限id,要变成权限的名称

用2表连接查询的时候不知道怎么弄,搜了半天可以用 a left join b on find_in_set(b.id,a.id) 这样的语句来查询

然后用group_concat()函数来分割权限的名称  ,再然后根据id分组进行查询

具体sql  

select a.*, group_concat(b.pri_name)  from my_role a left join my_privile
ge b on find_in_set(b.id,a.pri_id) group by a.id;

这样就可以查询出对应的权限名称.本人sql纯属菜鸟,

抱歉!评论已关闭.