Limiting array / group _concat in MySQL
2 answers
One solution would be to limit the rows in the group to the top two before calculating the aggregate.
SELECT t.i, GROUP_CONCAT(t.j)
FROM
(SELECT t1.i, t1.j
FROM mytable AS t1
LEFT JOIN mytable AS t2
ON (t1.i = t2.i AND t1.j >= t2.j)
GROUP BY t1.i, t1.j
HAVING COUNT(*) <= 2) AS t
GROUP BY t.i;
Another solution, if you know that the values in j
are of fixed length, is to simply use SUBSTRING()
for the result:
SELECT i, SUBSTRING( GROUP_CONCAT(j), 1, 3 )
FROM mytable
GROUP BY i;
0
source to share