Mysql查询以替代方式打印数据库值

时间:2014-01-30 10:37:17

标签: mysql select

我有一个数据库表,我必须按照以下方式打印

+---+--------+-----+    
|id | cat_id | name|    
+---+--------+-----+     
|1  |   1    | b   |    
|2  |   1    | ba  |    
|3  |   2    | c   |    
|4  |   2    | ca  |    
+---+--------+-----+

我需要一个mysql查询,它将以下列方式打印此表

+---+--------+-----+    
|id | cat_id | name|    
+---+--------+-----+     
|1  |   1    | b   |    
|3  |   2    | c   |    
|2  |   1    | ba  |    
|4  |   2    | ca  |    
+---+--------+-----+

提前致谢

1 个答案:

答案 0 :(得分:1)

select * from (
    select
    t.*,
    @catwise_rownum := if(@prevcat != cat_id, 1, @catwise_rownum + 1) as rownum,
    @prevcat := cat_id
    from
    your_table t,
    (select @catwise_rownum:=0, @prevcat:=null) var_init
    order by cat_id, id
) sq
order by rownum, cat_id