表结构
需求
取出除了超级管理员以外所有的用户信息,包括所属单位名称和角色列表,多个角色用逗号(,)隔开。
思路
先利用case/when语句根据unit_type类型的值获取用户所属的单位名称,再连接角色表获取每个用户所有的角色,在通过group by语句和group_contact函数得到所需的数据
实现
select
tbl_user.*,
group_concat( tbl_ur.role_id separator ',' ) roleIds,
group_concat( tbl_role.name separator ',' ) roleNames
from
(
select
tbl_user.*,
( case tbl_user.unit_type when 1 then tbl_college.id when 2 then tbl_dept.id end ) unitId,
( case tbl_user.unit_type when 1 then tbl_college.name when 2 then tbl_dept.name end ) unitName
from
mes_sys_user tbl_user
left join mes_sys_user_college tbl_uc on tbl_uc.user_id = tbl_user.id
left join mes_organization_college tbl_college on tbl_college.id = tbl_uc.college_id
left join mes_sys_user_department tbl_ud on tbl_ud.user_id = tbl_user.id
left join mes_organization_department tbl_dept on tbl_dept.id = tbl_ud.department_id
where
unit_type != 0
) tbl_user
left join mes_sys_user_role tbl_ur on tbl_ur.user_id = tbl_user.id
left join mes_sys_role tbl_role on tbl_role.id = tbl_ur.role_id
GROUP BY
tbl_user.id