MYSQL ORDER BY子句不起作用

时间:2017-12-14 10:22:34

标签: php mysql sql sorting sql-order-by

我有桌面任务:

id      title   date_task               complete

4948    Test 1  2017-11-10T11:00:00Z    1
4953    Test 2  2017-11-13T14:00:00Z    1
5028    Test 3  2017-11-21T11:00:00Z    1
5029    Test 4  2018-04-02T10:00:00Z    0

我想先排序:如果tasks.comeplete = 0顺序由ASC,其他人按顺序排序......

我的查询:

SELECT 
    *
FROM 
    `tasks`
ORDER BY 
    CASE WHEN tasks.complete = 0 THEN tasks.date_task END ASC, tasks.date_task DESC

我的结果:

id      title   date_task               complete
5028    Test 3  2017-11-21T11:00:00Z    1
4953    Test 2  2017-11-13T14:00:00Z    1
4948    Test 1  2017-11-10T11:00:00Z    1
5029    Test 4  2018-04-02T10:00:00Z    0

我想要结果:

id  title   date_task   complete
5029    Test 4  2018-04-02T10:00:00Z    0
5028    Test 3  2017-11-21T11:00:00Z    1
4953    Test 2  2017-11-13T14:00:00Z    1
4948    Test 1  2017-11-10T11:00:00Z    1

SQL FIDDLE:http://sqlfiddle.com/#!9/6f4a0/1

由于

2 个答案:

答案 0 :(得分:4)

这是一种方法:

SELECT *
FROM `tasks`
ORDER BY tasks.complete,
         CASE 
            WHEN tasks.complete = 0 THEN DATEDIFF(tasks.date_task, '1900-01-01') 
            ELSE DATEDIFF('1900-01-01', tasks.date_task) 
         END

Demo here

答案 1 :(得分:1)

这很简单:

SELECT *
FROM tasks
ORDER BY
    tasks.complete,
    CASE WHEN tasks.complete = 0 THEN tasks.date_task END,
    CASE WHEN tasks.complete = 1 THEN tasks.date_task END DESC