MySQL and GROUP_CONCAT() maximum length

前端 未结 7 983
难免孤独
难免孤独 2020-11-22 15:24

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 10

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 15:48

    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; 
    

提交回复
热议问题