group_concat on an empty join in MySQL

Posted by Yossarian on Stack Overflow See other posts from Stack Overflow or by Yossarian
Published on 2010-03-08T10:07:54Z Indexed on 2010/03/08 10:36 UTC
Read the original article Hit count: 196

Filed under:
|
|

Hello, I've got the following problem: I have two tables: (simplified)

+--------+    +-----------+
| User   |    | Role      |
+--------+    +-----------+
| ID<PK> |    | ID <PK>   |
+--------+    | Name      |
              +-----------+

and M:N relationship between them

+-------------+   
| User_Role   |   
+-------------+
| User<FK>    |
| Role<FK>    |
+-------------+

I need to create a view, which selects me: User, and in one column, all of his Roles (this is done by group_concat).

I've tried following:

SELECT u.*, group_concat(r.Name separator ',') as Roles FROM 
  User u
  LEFT JOIN User_Role ur ON ur.User=u.ID
  LEFT JOIN Role r ON ur.Role=r.ID
 GROUP BY u.ID;

However, this works for an user with some defined roles. Users without role aren't returned. How can I modify the statement, to return me User with empty string in Roles column when User doesn't have any Role?

Explanation: I'm passing the SQL data directly to a grid, which then formats itself, and it is easier for me to create slow and complicated view, than to format it in my code.

I'm using MySQL

© Stack Overflow or respective owner

Related posts about mysql

Related posts about join