MySQL: Group Concatination

Like row maximum and minimum there is another interesting function GROUP_CONCAT which returns values inside group as separated string. For example:

SELECT UserType, GROUP_CONCAT(ID) FROM `User` GROUP BY UserType;

will return:
1 | 1,2,3,4,5
2 | 6,7,8,9,10

Also it is possible to set custom separator (comma by default), sort order and eliminate repeated values by using DISTINCT:

SELECT
  UserType,
  GROUP_CONCAT(DISTINCT County ORDER BY Country SEPARATOR '; ')
FROM `User`
GROUP BY UserType;

But draw attention that GROUP_CONCAT has length limit 1024 symbols. It is possible to change that limit by updating global variable group_concat_max_len.

No Comment

No comments yet

Leave a reply