Mysql sorting table


Mysql sorting table

参考我之前的问题-如何在mysql查询中获得排序结果?

我正试图从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而不是按列id排序。cat_type必须按freefreepaid进行订购(请参阅第二个表列记录。)

注意:该表是动态的,记录数为"n"。

如何使用mysql查询实现这一点?

您可以枚举免费和付费的行。列举两个类别的最简单方法可能是使用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)

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

以下代码完成了任务:

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;

工作起来很有魅力。谢谢你的回答。