我正在尝试将我的角色名称进行分组
select
FirstName,
(
select GROUP_CONCAT(distinct role.Name SEPARATOR ', ')
from user_roles r
inner join users u ON u.Id = r.Userid
inner join roles role ON r.RoleId = role.Id
where role.Active = 1 and role.IsDeleted = 0 and r.UserId = u.Id
) As rloleList
from users;
我为所有用户使用相同的角色名称。
select
u.firstname,
group_concat(distinct r.name separator ', ') rolelist
from user_roles ur
inner join users u on u.id = ur.userid
inner join roles r on r.id = ur.roleid
where r.active = 1 and r.isdeleted = 0
group by u.id, u.firstname
我不确定您是否确实需要distinct
中的group_concat()
;它没有给定用户的重复角色(应该是给定您的架构),然后只需删除它以提高查询效率。
我正在尝试将我的角色名称进行分组
基本思想是:
select u.UserId, u.firstname,
group_concat(role_name separateor ', ') as roles
from user_roles ur inner join
users u
on u.Id = ur.Userid inner join
roles r
on r.RoleId = ur.Id
group by u.UserId, u.firstname;
[在大多数数据库中,user_roles
不会重复,因此在distinct
中不需要group_concat()
。如果可能重复,则将其包括在内。您的查询还有其他过滤器,您无需解释,因此我没有将它们包括在内。您可以只添加
where
子句:
where r.Active = 1 and r.IsDeleted = 0
如果需要这些附加条件。