Mysql排序表

时间:2015-02-12 13:17:24

标签: php mysql sql sorting

参考我之前的问题 - how to get a sorted result in mysql query?

我试图从MySQL查询中获取表的排序结果。

没有排序的表格如下:

+---------+---------------+
|      id |      cat_type |  
+---------+---------------+
|       1 |          free |
|       2 |          free |
|       3 |          free |
|       4 |          paid |
|       5 |          paid |
|       6 |          free |
|       7 |          free |
|       8 |          free |
|       9 |          paid |
|      10 |          free |
|      11 |          free |
|      12 |          free |
|      13 |          paid |
|      14 |          free |
+---------+---------------+

排序表必须如下:

+---------+---------------+
|      id |      cat_type |  
+---------+---------------+
|       1 |          free |
|       2 |          free |
|       4 |          paid |

|       3 |          free |
|       6 |          free |
|       5 |          paid |

|       7 |          free |
|       8 |          free |
|       9 |          paid |

|      10 |          free |
|      11 |          free |
|      13 |          paid |

|      12 |          free |
|      14 |          free |
+---------+---------------+

任务:为清晰起见,所有记录都按3分隔,并且应按列cat_type排序,而不是idcat_type必须按freefreepaid排序(请参阅第二表列记录。)

注意:该表是动态的,并且有'n'个记录。

如何使用mysql查询完成此操作?

2 个答案:

答案 0 :(得分:2)

您可以免费枚举这些行并付费。枚举两个类别的最简单方法可能是使用union all。然后你可以做算术来获得"免费"首先记录,然后"付费"记录。我想这会做到这一点:

select id, cat_type
from ((select t.*, @rn1 := @rn1 + 1 as seqnum
       from table t cross join (select @rn1 := 0) vars
       where cat_type = 'free'
       order by id
      ) union all
      (select t.*, @rn2 := @rn2 + 1 as seqnum
       from table t cross join (select @rn2 := 0) vars
       where cat_type = 'paid'
       order by id
      )
     ) t
order by (case when cat_type = 'free' then seqnum*1.0 else 2 * seqnum + 0.5 end)

答案 1 :(得分:0)

我的问题得到了答案,对我来说效果很好。

以下代码可以解决问题:

SET @i := 0; 
SET @j := 0.5; 
SELECT id, cat_type FROM 
(SELECT @i := @i + 1 as ordering, id, cat_type FROM table_name WHERE cat_type = 'free' 
 UNION 
 SELECT @j := @j + 2 as ordering, id, cat_type FROM table_name WHERE cat_type = 'paid') 
AS base_table 
ORDER BY ordering;

像魅力一样工作。谢谢你的回答。