MySQL ORDER BY结合最接近今天的两个日期

时间:2016-05-13 15:23:04

标签: php mysql sql

我有一张桌子

...         | reservation_from         | reservation_to         | ...
1           | 2016-05-13 10:00:00      | 2016-05-21 10:00:00    | ...
2           | 2016-05-13 20:00:00      | 2016-06-29 14:00:00    | ...
3           | 2016-05-01 10:00:00      | 2016-05-13 16:00:00    | ...

现在我必须订购并获得最近一天的预订。

例如现在是2016-05-13,所以无论预订是开始还是结束,我都必须得到最接近当前时间的结果。我想点那样订购

...         | reservation_from         | reservation_to         | ...
1           | 2016-05-13 10:00:00      | 2016-05-21 10:00:00    | ...
2           | 2016-05-01 10:00:00      | 2016-05-13 16:00:00    | ...
3           | 2016-05-13 20:00:00      | 2016-06-29 14:00:00    | ...

如您所见,第二个结果reservation_from是05-01,但其reservation_to小于第3 reservation_from

我不知道我是否清楚这个问题,如果没有,请评论它我应该指定更多。

2 个答案:

答案 0 :(得分:2)

You want to order by the lesser time difference to now:

select *
from mytable
order by 
  least(abs(timestampdiff(second, now(), reservation_from)),
        abs(timestampdiff(second, now(), reservation_to)));

You can add futher criteria in order to deal with ties of course.

答案 1 :(得分:1)

USE LEAST. Will calculate the difference between each field and today, choose the smaller one.

 SELECT *
 FROM YourTable
 ORDER BY LEAST( ABS(TIMEDIFF(reservation_from, CURDATE()),
                 ABS(TIMEDIFF(reservation_to  , CURDATE())
               )