MySQL Order By:条件多列

时间:2016-01-12 15:33:40

标签: mysql sql-order-by

我有一个按入境日期排序的清单:

  • JOB C,en-GB,2016-01-12 08:00:00
  • JOB B,en-GB,2016-01-12 08:10:00
  • JOB A,en-GB,2016-01-12 08:20:00

让我们说我现在添加:

  • JOB B,fr-FR,2016-01-12 08:30:00

在当前查询中,列表如下所示:

  • JOB C,en-GB,2016-01-12 08:00:00
  • JOB B,en-GB,2016-01-12 08:10:00
  • JOB A,en-GB,2016-01-12 08:20:00
  • JOB B,fr-FR,2016-01-12 08:30:00

请参阅http://sqlfiddle.com/#!9/8d61d7/2

我需要结果如下:

  • JOB C,en-GB,2016-01-12 08:00:00
  • JOB B,en-GB,2016-01-12 08:10:00
  • JOB B,fr-FR,2016-01-12 08:30:00
  • JOB A,en-GB,2016-01-12 08:20:00

因此,初始排序是由created_at进行的,但是JOB B,fr-FR现在低于JOB B,en-GB记录。

对于错综复杂的解释感到抱歉......

1 个答案:

答案 0 :(得分:1)

如果是这种情况,我宁愿使用UNION ALL并在select语句中添加“id”。 这是代码

SELECT *
FROM (
select 1 as id, name, job, created_at from yourtable where created_at <= '2016-01-12 08:10:00'
union all
select 2 as id, name, job, created_at from yourtable where job = 'fr-FR'
union all
select 3 as id, name, job, created_at from yourtable where created_at = '2016-01-12 08:20:00'
) x
order by x.id, x.created_at