SQL:先显示未来的记录,再显示其余的。均按 create_date DESC

SQL: first show future records, then the rest. Both by create_date DESC

我table喜欢:

id  | create_date | start_date | status
112 | 2015-03-13  | 2015-03-14 |   1
106 | 2015-03-07  | 2015-03-19 |   2
105 | 2015-03-06  | 2015-03-29 |   1
104 | 2015-03-05  | 2015-03-29 |   1
101 | 2015-03-03  | 2015-03-20 |   1
100 | 2015-03-01  | 2015-03-03 |   1
 99 | 2015-03-01  | 2015-03-06 |   2

现在,我想 select 并通过以下方式订购这些记录:

  1. 带有 status = 1start_date >= NOW() 的记录必须排在第一位,按 create_date DESC 排序 - 带有 status = 1 and start_date >= now() 的最新记录将排在第一位。这些是 'active'

  2. 其他记录(即status = 0status = 2status = 1 AND start_date < NOW()的记录)将处于活跃状态,按create_date DESC排序。

预期输出:

id  | create_date | start_date | status
112 | 2015-03-13  | 2015-03-14 |   1
105 | 2015-03-06  | 2015-03-29 |   1
104 | 2015-03-05  | 2015-03-29 |   1
101 | 2015-03-03  | 2015-03-20 |   1
106 | 2015-03-07  | 2015-03-19 |   2
100 | 2015-03-01  | 2015-03-03 |   1
 99 | 2015-03-01  | 2015-03-06 |   2 -- behind id 100 not because of higher status, but because of create_date (I store datetime instead of date).

SQL查询:

SELECT a.[columns],
       d.[columns],
       r1.[columns],
       r2.[columns]
FROM articles a
JOIN reg r1
    ON r1.id = a.locality_id
LEFT JOIN reg r2
    ON r2.id = r1.parent_id
LEFT JOIN `d` AS d
    ON d.id = a.demander_id
WHERE a.s_id = 1
ORDER BY (a.status = 1 AND a.start_date >= NOW()) DESC,
         a.create_date DESC

当前输出:

id  | create_date | start_date | status
105 | 2015-03-06  | 2015-03-29 |   1
104 | 2015-03-05  | 2015-03-29 |   1
101 | 2015-03-03  | 2015-03-20 |   1
112 | 2015-03-13  | 2015-03-14 |   1
106 | 2015-03-07  | 2015-03-19 |   2
100 | 2015-03-01  | 2015-03-03 |   1
 99 | 2015-03-01  | 2015-03-06 |   2

它returns我以后的记录在另一个status = 1之前,没关系,但按start_date DESC排序。

这个DESC的意思应该是'order by a condition before which returns 1 or 0 desc (first records when condition is true, than the rest) and then order records by create date from newest'。但它还有别的作用。

有什么想法吗?

你很接近,但你需要比较 CURRENT_DATE() 而不是 NOW():

ORDER BY CASE
    WHEN status = 1 AND start_date >= CURRENT_DATE() THEN 1
    ELSE                                                  2
END, create_date DESC

如果当前日期时间是 2015-03-14 00:00:01 那么:

  • 2015-03-14 >= NOW()不匹配
  • 2015-03-14 >= CURRENT_DATE() 匹配