Search code examples
phpmysqllimitgroup-concat

PHP MySQL GROUP_CONCAT Limit


I couldn't find wether this was possible so, is there any option to limit a GROUP_CONCAT in MySQL-function?

E.g.:

GROUP_CONCAT(ColName ORDER BY ColName DESC LIMIT 5)

I don't want to use a subquery since this will seriously slow down the performance. I can slice the array later in PHP, but I was wondering or MySQL had an option to achieve this in MySQL already.


Solution

  • No, but you can do this:

    SUBSTRING_INDEX(GROUP_CONCAT(ColName ORDER BY ColName DESC), ',', 5)
    

    You may want to pay attention to the group concat maximum length (see group_concat_max_len), if the intermediate string might be larger than 1024 characters. You can change the default.