基于“类别”字段显示行

时间:2015-10-17 14:32:02

标签: mysql sql

我有一张桌子,我在那里查询所有字段。那部分效果很好。但是,它没有显示所需的输出。我想让行显示不同的类别。换句话说,避免背靠背显示相同的类别。我尝试过使用DISTINCT,但没有效果。是否存在基于category的显示基础。如何实现以下输出? SQLFIDDLE

期望输出

game_id game_name                   category
------- --------------------------- --------
634266  street fighter v            fighting
684244  minecraft                   adventure
779343  call of duty modern warfare fps
858168  need for speed - rivals     racing
819837  mortal kombat x             fighting
983565  assassin's creed syndicate  adventure
840832  counter-strike              fps
858768  gran turismo                racing

当前输出

game_id game_name                   category
------- --------------------------- --------
634266  street fighter v            fighting
684244  minecraft                   adventure
779343  call of duty modern warfare fps
819837  mortal kombat x             fighting
840832  counter-strike              fps
858168  need for speed - rivals     racing
858768  gran turismo                racing
983565  assassin's creed syndicate  adventure

1 个答案:

答案 0 :(得分:0)

我知道,您希望每个类别出现一次,然后循环显示它们。这是一种方法。枚举类别,然后按枚举排序:

select vg.game_id, vg.game_name, vg.category
from (select vg.*,
             (@rn := if(@c = vg.category, @rn + 1,
                        if(@c := vg.category, 1, 1)
                       )
             ) as rn
      from videogames vg cross join
           (select @c := '', @rn := 0) params
      order by vg.category, vg.game_id
     ) vg
order by rn,
      field(category, 'fighting', 'adventure', 'fps', 'racing');

SQL小提琴是here