如何编写查询以获得该结果

时间:2015-03-29 21:34:58

标签: mysql

我有一个名为myTable的表包含一些数据,如下面的

id type name
1   1    A
2   2    B
3   3    C
4   2    D
5   3    E
6   3    F

如何编写查询以获得如下id:name

之类的结果
type1  type2 type3
1:A     2:B   3:C
null    4:D   5:E
null    null  6:F

1 个答案:

答案 0 :(得分:1)

通常,这种类型的操作在应用程序层中更容易完成。但是,您可以通过枚举每种类型的每一行然后按它进行聚合来完成此操作。

我认为这可以满足您的需求:

select max(case when type = 1 then concat_ws(':', id, type) end) as type1,
       max(case when type = 2 then concat_ws(':', id, type) end) as type2,
       max(case when type = 3 then concat_ws(':', id, type) end) as type3
from (select t.*,
             (@rn := if(@t = type, @rn + 1,
                        if(@t := type, 1, 1)
                       )
             ) as rn
      from table t cross join
           (select @rn := 0, @t := -1) vars
      order by type, id
     ) t
group by rn
相关问题