0

Concat multiple rows in one

Posted July 2nd, 2010 in , by thomas

I will take an example to explain this tip.

imagine we want to export our drupal users with their roles. if a user has 3 roles, the result of the join query will be 3 rows for him.

Using GROUP_CONCAT will give us all roles in one single row.

SELECT u.uid, u.name, u.mail,
 GROUP_CONCAT(DISTINCT r.name SEPARATOR '/') as roles
from users u
 inner join users_roles ur on ur.uid = u.uid
 inner join role r using(rid)
 GROUP BY u.uid

notice here the GROUP BY u.uid (otherwise all users will be concatenated in 1 row).

see the syntax of this function

Leave a Reply