GROUP_CONCAT with limit

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

    You can simulate the partitioned row_number using user variables and then limit rows and apply group_concat:

    select p.id,
        group_concat(s.title separator ', ') as skills
    from player p
    left join (
        select distinct ps.player_id,
            ps.skill_id,
            @rn := if(@player_id = player_id, @rn+1, if(@player_id := player_id, 1, 1)) as seqnum
        from player_skills ps
        cross join (select @rn := 0, @player_id := null) x
        where ps.value > 2
        order by player_id, value desc
        ) ps on p.id = ps.player_id and ps.seqnum <= 3
    left join skill s on ps.skill_id = s.id
    group by p.id;
    

    Demo

    This method doesn't require any table to read more than once.

提交回复
热议问题