GROUP_CONCAT with limit

前端 未结 7 1174
甜味超标
甜味超标 2020-11-27 15:34

I have table with player-s in many-to-many relation with skill-s

The goal is to list the players and their \"top 3 skills\" with a single q

7条回答
  •  旧巷少年郎
    2020-11-27 16:20

    Here's another solution. It includes an arbitrary mechanism for resolving ties, and employes a schema slightly differing from yours...

    SELECT a.player_id
         , GROUP_CONCAT(s.title ORDER BY rank) skills
      FROM
         ( SELECT x.*, COUNT(*) rank
             FROM player_skills x
             JOIN player_skills y 
               ON y.player_id = x.player_id
              AND (y.value > x.value
               OR (y.value = x.value AND y.skill_id <= x.skill_id))
            GROUP 
               BY player_id, value, skill_id
           HAVING COUNT(*) <= 3
         ) a
      JOIN skill s
        ON s.skill_id = a.skill_id
     GROUP 
        BY player_id;
    

    http://sqlfiddle.com/#!2/34497/18

    Incidentally, if you have a presentation layer/application-level code, then consider doing all the GROUP_CONCAT stuff there. It's more flexible.

提交回复
热议问题