MySQL查询:如何在每个品牌中找到前5个图像?

时间:2014-01-07 09:39:04

标签: mysql sql group-concat top-n

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

2 个答案:

答案 0 :(得分:4)

使用SUBSTRING_INDEX

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

<强> fiddle

答案 1 :(得分: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 Fiddle