如何按多个时间戳字段排序并 return 按时间顺序排序?

How to order by multiple timestamp fields and return them in chronological order?

我有 table 个帖子(新闻),但它们可以有不同的日期属性,其中一些可能未设置 (0)。我想在所有字段上排序 DESC,然后得到一个遵循时间顺序的结果,而不是我在查询中给出的顺序。

title | pubdate     | startdate  | enddate     | closedate  |
------------------------------------------------------------
exm1  | 1271887200  |          0 |          0  |          0 |
exm2  | 1291071600  |          0 |          0  |          0 |
exm3  |          0  | 1496102400 | 1496361600  |          0 |
exm4  | 1496620800  |          0 |          0  |          0 |
exm5  |          0  | 1501545600 | 1501891200  | 1496966400 |
exm6  |          0  | 1493856000 | 1496361600  |          0 |

相关字段是 "pubdate"、"startdate" 或 "closedate"。所以我所做的只是将它们放入我的 ORDER BY 语句中:

SELECT * FROM news ORDER BY closedate DESC, startdate DESC, pubdate DESC

这当然有效,但我注意到这总是将带有 "closedate" 的行放在结果的前面,然后是 "startdate" 结果等。并且排序只发生在那些 切片 而不是所有值。它们被视为不同的集合,缝合在一起。

因此结果为:exm5, exm3, exm6, exm4, exm2, exm1

但我想要以下内容:exm5、exm4、exm3、exm6、exm2、exm1

原因:

- exm5 close is 06.09.2017 (and pub is 0)
- exm4 pub   is 06.05.2017 (and close is 0 and enddate is 0)
- exm3 start is 05.30.2017 (and close is 0 and pub is 0)
- exm6 start is 05.04.2017 (and close is 0 and pub is 0)

我可以按代码应用此排序,但我想在此查询中使用 LIMIT 和偏移量,以保持分页顺序。

我觉得我必须以某种方式合并这些值并在单个字段上排序,但我不知道该怎么做,或者仅 MYSQL 是否可行。

有什么想法吗?谢谢

也许greatest()如你所愿:

ORDER BY GREATEST(closedate, startdate, pubdate) DESC

您似乎在使用 0 作为缺失值。如果是这样,这很好。如果您实际上有 NULL,那么逻辑需要处理它们。

编辑:

如果您有优先权,请使用:

ORDER BY (CASE WHEN closeddate > 0 THEN closeddate
               WHEN startdate > 0 THEN startdate
               ELSE pubdate
          END)

这适用于 NULL 个值。