如何在mysql查询中获得排序结果?

2022-01-23 00:00:00 sql subquery php mysql

我正在尝试从 MySQL 查询中获取排序结果,但我不知道如何进行查询.

I am trying to get a sorted result from a MySQL query and i dont have any idea of making the query.

我有一个示例 Mysql 表如下:

I have a example Mysql table as follows :

     id | cat_type
     1  |  free
     2  |  free
     3  |  free
     4  |  free
     5  |  paid
     6  |  paid
    ... |  ...
    ... |  ...
    ... |  ...
   and it goes on.

上表的结果应该如下:

     id | cat_type
     1  | free 
     2  | free 
     5  | paid

     3  | free 
     4  | free 
     6  | paid

    ... | free
    ... | free
    ... | paid
  and goes on(should be sorted)

总的结果应该被拆分为 3.在前三个结果中,前两个应该是 free 并且下一个应该是 paid 同样所有剩余的结果应该分为两个free和一个paid.

The total result should be splitted as 3. In the first three result, first two should be free and the next one should be paid likewise all the remaining result should be sorted as two free and one paid.

知道如何使用查询来完成此任务吗?

Any idea how to accomplish this using a query?

注意:最重要的是它应该被分类为两个免费和一个付费.不是 ID.

NOTE : The most important is that it should be sorted as two free and one paid. Not by ID.

谢谢.

推荐答案

对于你特定的数据,你可以这样做:

For you particular data, you could do:

order by (case when cat_type = 'free' then id*1.0
               else 2*id - 7.5
          end)

这似乎非常神秘.如果您有更普遍的问题,您应该提出另一个问题,更好地描述您真正想要完成的任务.

This seems very arcane. If you have a more general problem, you should ask another question, giving a better description of what you really want to accomplish.

相关文章