我有一个帖子(新闻)表,但它们可以具有不同的日期属性,其中一些属性可能未设置(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 |
相关字段为“发布日期”、“开始日期”或“关闭日期”。所以我所做的只是将它们放入我的 ORDER BY 语句中:
SELECT * FROM news ORDER BY closedate DESC, startdate DESC, pubdate DESC
这当然有效,但我注意到这总是将带有“closedate”的行放在结果的前面,然后是“startdate”结果,等等......并且排序仅发生在这些切片内 em> 并且不跨越所有值。它们被视为不同的集合,缝合在一起。
因此,结果为: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
值。
关于mysql - 如何按多个时间戳字段排序并按时间顺序返回它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411644/