GROUP_CONCAT with limit

前端 未结 7 1210
甜味超标
甜味超标 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:21

    One somewhat hacky way to do it is to post-process the result of GROUP_CONCAT:

    substring_index(group_concat(s.title SEPARATOR ','), ',', 3) as skills
    

    Of course this assumes that your skill names don't contain commas and that their amount is reasonably small.

    fiddle

    A feature request for GROUP_CONCAT to support an explicit LIMIT clause is unfortunately still not resolved.

    UPDATE: As user Strawberry points out, the table player_skills should have the tuple (player_id, skill_id) as its primary key, otherwise the schema allows for the same skill to be assigned to a player multiple times, in which case group_concat would not work as expected.

提交回复
热议问题