SELECT `u`.`gid` AS `group_id`,
`g`.`name` AS `group_name`,
GROUP_CONCAT(DISTINCT `r`.`name` SEPARATOR ",") AS roles,
FROM (
SELECT `u`.`user` AS `user`, `u`.`gid` AS `gid`, `ru`.`id` AS `role`
FROM `users` AS `u`
LEFT JOIN `roles_users` AS `ru`
ON `u`.`user` = :user_id AND `ru`.`user` = `u`.`user`
UNION SELECT `u`.`user` AS `user`, `u`.`gid` AS `gid`, `rg`.`id` AS `role`
FROM `users` AS `u`
LEFT JOIN `roles_groups` AS `rg`
ON `u`.`user` = :user_id AND `rg`.`gid` = `u`.`gid`
) AS `ur`
INNER JOIN `groups` AS `g` ON `g`.`id` = `ur`.`gid`
LEFT JOIN `roles` AS `r` ON `r`.`id` = `ur`.`role`