所以我有一个包含几张表的数据库。主要是Plant。我还有一个包含 plant_id、effect_id 的 PlantEffects 表。我需要做的是选择 Plants,但根据 PlantEffects.effect_id 选择排名前 5 的 PlantEffects。所以它会出来
|ID|NAME|top_effect_ids|
|1 |abc |1,4,5,6,7 |
|2 |def |3,2,9,7,5 |
最佳答案
如果我对您的问题的理解正确,您希望将前五个 effect_id
(按计数)放入 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
关于mysql获取id数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11703171/