Use SUBSTRING_INDEX
SELECT
brand_id,
SUBSTRING_INDEX(GROUP_CONCAT(image_id SEPARATOR ','),',',5) AS image_ids
FROM Table1
GROUP BY brand_id
Question
The following data in mysql table.
brand_id|image_id|downloads
--------|--------|---------
8 |9 |8
35 |2829 |4
28 |2960 |3
28 |2961 |3
28 |3041 |3
35 |2831 |3
28 |2965 |3
35 |2832 |3
28 |2959 |2
28 |2976 |2
35 |2894 |2
How can I find top 5 images with GROUP_CONCAT
function in each brand ?
And I would like to get following in return :
brand_id|image_ids
--------|--------------------------
8 |9
35 |2829,2831,2832,2894
28 |2960,2961,3041,2965,2959
Solution
Use SUBSTRING_INDEX
SELECT
brand_id,
SUBSTRING_INDEX(GROUP_CONCAT(image_id SEPARATOR ','),',',5) AS image_ids
FROM Table1
GROUP BY brand_id
OTHER TIPS
If your pint is to get the top 5 of each group, then the below sql will give you the result:
SELECT A.brand_id, GROUP_CONCAT(A.image_id)
FROM (
SELECT t1.* FROM Table1 AS t1
LEFT JOIN Table1 AS t2
ON t1.brand_id = t2.brand_id AND t1.image_id = t2.image_id AND t1.downloads <= t2.downloads
GROUP BY t1.brand_id, t1.image_id HAVING COUNT(*) <= 5
) A GROUP BY A.brand_id