I somehow need this feature,but MySQL doesn't support it at this moment.
I'm using GROUP_CONCAT(CONCAT(...))
to generate a xml-like stuff.
But when the size exceeds the limit,the xml is just broken!
So I have to somehow make it only retrieve 5 rows !
An example for Charles answer:
basic:
extended:
CAST can be useful if result are truncated by buffer:
Not really an answer to your question but a ref for other people who also would want to use a LIMIT clause in GROUP_CONCAT():
A feature-request was filed long ago to MySql developers. Not yet implemented :-(
You can simulate the partitioned row_number using user variables and then limit rows and apply group_concat:
Consider the following table:
and data:
And we want is top 3 (in order of latest id) value per category concatenated:
Output:
Here is a demo of this.
For those cases where you cannot use a temp table, The best way I know of is to select an obscure separator and then truncate starting at the first instance of said character. This example uses the NUL character.
select substring_index(group_concat(field separator '\0'), '\0', 5) from table;
Where
field
is the name of the field,5
is the number of results.The drawback is if your first row contains that character, it will be a partial result.
A workaround would be to replace
'\0'
with a longer random string.It's good to know that
field
could be replaced to include more information usingconcat
.Keep in mind the
group_concat_max_len
defaults to 1024 characters, so you should look into changing that either globally or within your application if you want more than that.I've worked around this using
SUBSTRING_INDEX
.For example:
Use a temporary table / subquery to limit results? Without seeing your query, it'll be hard to give solid advice for that route.
However, you may find the
group_concat_max_len
setting to be more useful. It controls the maximum length of aGROUP_CONCAT
operation, in string length. Raise it to prevent brokenGROUP_CONCAT
s, when you can't afford to limit results.