2

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.

2

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you have missed one ')' after desc
@GordonLinoff, great solution, thanks. The 1024 will be large enough, since I will only return 5 integers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.