在MySQL中对日期的ORDER BY进行排序时,我正在尝试在今天之后对ASC进行排序,并在今天之前将DESC排序为日期。
我正在做类似的事情:
SELECT * FROM test ORDER BY IF(created >= NOW(), created, 1) ASC, created DESC
这给了我一些理想的结果:
ID CREATED
8 May, 10 2014 11:15:00+0000
7 May, 03 2014 20:47:00+0000
5 May, 02 2014 14:00:00+0000
4 April, 30 2014 17:41:00+0000
3 April, 30 2014 17:00:00+0000
1 April, 21 2014 03:30:00+0000
6 March, 23 2014 12:00:00+0000
9 May, 20 2014 20:45:00+0000
10 July, 02 2014 20:30:00+0000
2 June, 30 2015 11:16:00+0000
今天是DESC,今天之后是ASC。但是,我希望在结果的顶部看到ID 9,10,2的块。
对于如何做到这一点的任何想法表示赞赏。
答案 0 :(得分:1)
为order by
添加一个附加条件,这是日期是过去还是将来的二进制指示符:
SELECT *
FROM test
ORDER BY (created >= NOW()) desc,
IF(created >= NOW(), created, NULL) ASC,
created DESC;
答案 1 :(得分:0)
如何将其拆分为2个sql查询然后将结果合并?
(SELECT * FROM test WHERE created >= NOW() ORDER BY created ASC)
UNION
(SELECT * FROM test WHERE created < NOW() ORDER BY created DESC)