Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hack MySQL GROUP_CONCAT to fetch a limited number of rows?

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 !

like image 627
Misier Avatar asked Oct 05 '09 21:10

Misier


2 Answers

I've worked around this using SUBSTRING_INDEX.

For example:

SELECT SUBSTRING_INDEX(GROUP_CONCAT(Field1 SEPARATOR ','), ',', [# of elements to return])
FROM Table1;
like image 170
Denis Dupere Avatar answered Sep 23 '22 10:09

Denis Dupere


An example for Charles answer:

basic:

SELECT GROUP_CONCAT( field ) FROM ( SELECT field FROM table LIMIT 200 )

extended:

CAST can be useful if result are truncated by buffer:

SELECT CAST( GROUP_CONCAT( field ) AS CHAR(2048) ) FROM ( SELECT field FROM table LIMIT 200 )
like image 40
rekans Avatar answered Sep 20 '22 10:09

rekans