4

我有一个日期列,我正在使用 order by 子句。

我想在顶部显示今天日期附近的记录,然后在底部显示过去的所有记录。

我想用单个查询来做到这一点。

我试过这个

SELECT *, DATEDIFF(`date`, CURDATE()) AS diff  FROM `post` order by diff

这个查询的问题是这将首先显示过去的记录,如果我使用降序,那么远离今天的记录将位于顶部。

我怎样才能做到这一点?

任何帮助将不胜感激。

4

5 回答 5

9

你应该能够做到这一点:

SELECT *, DATEDIFF(`date`, CURDATE()) AS diff  FROM `post`
order by CASE WHEN diff < 0 THEN 1 ELSE 0 END, diff

这将强制过去的任何日期在当前日期或未来日期之后排序。

于 2012-07-09T13:53:41.147 回答
3

尝试这个

   SELECT *, DATEDIFF(`date`, CURDATE()) AS diff  FROM `post` order by ABS(diff)
于 2012-07-09T13:51:29.250 回答
1

你需要ORDER BY像这样下降:

 SELECT *, DATEDIFF(`date`, CURDATE()) AS diff  
 FROM `post ORDER BY diff DESC;
于 2012-07-09T13:50:44.803 回答
0

为什么没有简单的旧日期顺序?

 SELECT *, DATEDIFF(`date`, CURDATE()) AS diff  
 FROM `post ORDER BY date DESC;
于 2012-07-09T13:51:42.067 回答
0

由于您不希望将来的结果太远,因此只需从结果集中删除这些结果:

SELECT *, DATEDIFF(`date`, CURDATE()) AS diff FROM `post` 
WHERE `date` < date_add(CURDATE(), INTERVAL 1 DAY)
ORDER BY diff DESC
于 2012-07-09T13:52:05.973 回答