Michael Frey
Michael Frey

Reputation: 918

Mysql group concat on double join

I have a user table from which I want all values, so I have this query:

SELECT tbl_user.* FROM tbl_user

Now I want one additional column in this result which shows all roles this user has, (or nothing if there are no roles for the user). The role information comes from two additional tables.

The first table contains these two values: userid, roleid The second table contains roleid and role_name.

So the group concat needs to get all role names based on the roleid's in table1.

I have tried several different ways to do this, but I don't succeed. Either I get only one result with several times the same rolename, or no result at all.

Thanks for your help

Michael

Upvotes: 0

Views: 802

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

Update: added LEFT JOIN for users with no role.

SELECT
  tbl_user.*,
  GROUP_CONCAT(role_name) AS roles
FROM 
  tbl_user LEFT JOIN tbl_roles ON tbl_user.userid = tbl_roles.userid
  JOIN tbl_rolenames ON tbl_roles.roleid = tbl_rolenames.roleid
GROUP BY tbl_user.userid

Note that MySQL will permit a GROUP BY on fewer columns than appear in the SELECT list in total, but in other RDBMS you would need to explicitly list out the columns in tbl_user and include them in the GROUP BY, or do an additional self join against tbl_user to get the remaining columns from that table.

Something like:

SELECT 
  urole.userid,
  uall.username,
  uall.name,
  uall.othercols,
  urole.roles
FROM
  tbl_user uall JOIN (
  SELECT 
    tbl_user.userid, 
    GROUP_CONCAT(role_name) AS roles
  FROM 
    tbl_user LEFT JOIN tbl_roles ON tbl_user.userid = tbl_roles.roleid
    JOIN tbl_rolenames ON tbl_roles.roleid = tbl_rolenames.roleid
  GROUP BY tbl_user.userid
) urole ON uall.userid = urole.userid

Upvotes: 2

Related Questions