我有一个日期列,我正在使用 order by 子句。
我想在顶部显示今天日期附近的记录,然后在底部显示过去的所有记录。
我想用单个查询来做到这一点。
我试过这个
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff FROM `post` order by diff
这个查询的问题是这将首先显示过去的记录,如果我使用降序,那么远离今天的记录将位于顶部。
我怎样才能做到这一点?
任何帮助将不胜感激。
你应该能够做到这一点:
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff FROM `post`
order by CASE WHEN diff < 0 THEN 1 ELSE 0 END, diff
这将强制过去的任何日期在当前日期或未来日期之后排序。
尝试这个
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff FROM `post` order by ABS(diff)
你需要ORDER BY
像这样下降:
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff
FROM `post ORDER BY diff DESC;
为什么没有简单的旧日期顺序?
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff
FROM `post ORDER BY date DESC;
由于您不希望将来的结果太远,因此只需从结果集中删除这些结果:
SELECT *, DATEDIFF(`date`, CURDATE()) AS diff FROM `post`
WHERE `date` < date_add(CURDATE(), INTERVAL 1 DAY)
ORDER BY diff DESC