2014-10-16 79 views
0

我的查询中有一个复杂的排序问题。MySQL complex ORDER BY issue

原始,无序数据:

+------+--------+-----------+ 
| 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是最近添加:

    +------+--------+-----------+ 
    | 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以1
  • 的action_id然后用上升action_ids具有相同JOB_ID的条目
  • 然后1所
  • 循环往复

编辑的下一个最近的action_id:我我无法在列表中添加列以帮助排序,正如我在其他解决方案中看到的排序问题。

任何帮助,非常感谢!

回答

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)); 
+0

谢谢,这工作完美。在'ORDER BY'中也可以完成所有的积分! – Matt 2014-10-17 08:03:04

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 
+0

忘记一些参考表在子查询中。 – 2014-10-16 17:16:45