MySQL复杂的ORDER BY问题

时间:2014-10-16 16:51:50

标签: mysql sql-order-by

我的查询中有一个复杂的排序问题。

原始无序数据:

+------+--------+-----------+
| id   | job_id | action_id |
+------+--------+-----------+
|    1 |      2 |         1 |  
|    2 |      2 |         2 |  
|    3 |      1 |         1 |  
|    4 |      2 |         3 |  
|    5 |      4 |         1 |  
|    6 |      1 |         2 |  
|    7 |      3 |         1 |  
|    8 |      3 |         2 |  
|    9 |      4 |         2 |  
+------+--------+-----------+

必填排序:

+------+--------+-----------+
| id   | job_id | action_id |
+------+--------+-----------+
|    7 |      3 |         1 |  
|    8 |      3 |         2 |  
|      |        |           |    * blank lines added for clarity,
|    5 |      4 |         1 |      not desired in actual data
|    9 |      4 |         2 |  
|      |        |           | 
|    3 |      1 |         1 |  
|    6 |      1 |         2 |  
|      |        |           | 
|    1 |      2 |         1 |  
|    2 |      2 |         2 |  
|    4 |      2 |         3 |  
+------+--------+-----------+

这种排序背后的理论:

  • 最大的ID是最近添加的条目
  • action_id为1
  • 的最新ID
  • 后跟具有相同job_id
  • 的提升action_ids的条目
  • 然后是下一个最近的action_id 1
  • ad infinitum

编辑:我无法在表格中添加列以帮助排序,正如我在其他解决方案中看到的那样排序问题。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

我最好的拍摄是:

SELECT * FROM tbl 
    ORDER BY FIND_IN_SET(job_id,
        (SELECT GROUP_CONCAT(job_id ORDER BY ID DESC) 
         FROM tbl WHERE action_id = 1));

答案 1 :(得分:0)

我没有找到方法轻松完成这项工作,您如何看待以下代码:

select c.id, c.job_id, c.action_id
  from (select a.id, a.job_id, a.action_id, min(b.id) as related_id
          from myTable a 
          inner join myTable b
             on a.job_id=b.job_id 
         group by a.job_id) c
 group by c.id
 order by c.related_id desc, c.action_id