2

mysql表中的以下数据。

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  

如何GROUP_CONCAT在每个品牌中找到前 5 个具有功能的图片?我想得到以下回报:

brand_id|image_ids                
--------|--------------------------
8       |9                       
35      |2829,2831,2832,2894     
28      |2960,2961,3041,2965,2959
4

2 回答 2

4

使用SUBSTRING_INDEX

SELECT
  brand_id,
  SUBSTRING_INDEX(GROUP_CONCAT(image_id SEPARATOR ','),',',5) AS image_ids
FROM Table1
GROUP BY brand_id

小提琴

于 2014-01-07T09:44:48.350 回答
3

如果您的品脱是获得每组的前 5名,那么下面的 sql 将为您提供结果:

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

SQL小提琴

于 2014-01-07T09:55:24.723 回答