2012-07-28 75 views
1

所以我有一個數據庫與幾個表。主要是植物。我也有一個PlantEffects表,它具有plant_id,effect_id。我需要做的是選擇植物,但PlantEffects.effect_id數量排在前5位的PlantEffects。所以它會出來作爲mysql獲取ID數組

|ID|NAME|top_effect_ids| 
|1 |abc |1,4,5,6,7  | 
|2 |def |3,2,9,7,5  | 
+0

你可以發佈你的表架構和一些示例數據嗎?這會讓你更容易回答你的問題。 – 2012-07-28 17:36:08

回答

1

如果我正確理解你的問題,你想獲得前五名effect_id S(由計數)到CSV列表

你可以做這樣的事情:

SELECT 
    a.id, 
    a.name, 
    SUBSTRING_INDEX(GROUP_CONCAT(b.effect_id ORDER BY b.effectcnt DESC), ',', 5) AS top_effect_ids 
FROM 
    plants a 
INNER JOIN 
(
    SELECT plant_id, effect_id, COUNT(1) AS effectcnt 
    FROM planteffects 
    GROUP BY plant_id, effect_id 
) b ON a.id = b.plant_id 
GROUP BY 
    a.id, a.name