Search code examples
mysqlgroup-concat

MySQL and GROUP_CONCAT() maximum length


I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

I'm very well aware that I can change the param group_concat_max_len to increase this limit:

SET SESSION group_concat_max_len = 1000000;

However, on the server I'm using, I can't change any param. Not by using the preceding query and not by editing any configuration file.

So my question is: Is there any other way to get the output of a multiple row query into a single string?


Solution

  • CREATE TABLE some_table (
      field1 int(11) NOT NULL AUTO_INCREMENT,
      field2 varchar(10) NOT NULL,
      field3 varchar(10) NOT NULL,
      PRIMARY KEY (`field1`)
    );
    
    INSERT INTO `some_table` (field1, field2, field3) VALUES
    (1, 'text one', 'foo'),
    (2, 'text two', 'bar'),
    (3, 'text three', 'data'),
    (4, 'text four', 'magic');
    

    This query is a bit strange but it does not need another query to initialize the variable; and it can be embedded in a more complex query. It returns all the 'field2's separated by a semicolon.

    SELECT result
    FROM   (SELECT @result := '',
                   (SELECT result
                    FROM   (SELECT @result := CONCAT_WS(';', @result, field2) AS result,
                                   LENGTH(@result)                            AS blength
                            FROM   some_table
                            ORDER  BY blength DESC
                            LIMIT  1) AS sub1) AS result) AS sub2;