我需要获取下一个日期和上一个日期

表结构如下

| auto_id | id | next_date  | next_activity |
|    1    |  1 | 22-12-2012 |     -         |
|    2    |  1 | 25-12-2012 |     -         |
|    3    |  1 | 26-12-2012 |     -         |
|    4    |  1 | 28-12-2012 |     -         |


所以我需要第二天和前一天
next_day =当前日期之后的next_date
上一个日期=当前日期之前的下一个日期

(SELECT * FROM `activity` WHERE id = 1 and next_date > CURDATE() order by next_date asc limit 1)
UNION
(SELECT * FROM `activity` WHERE id = 1 and next_date = CURDATE() )
UNION
(SELECT * FROM `activity` WHERE id = 1 and next_date < CURDATE() order by next_date desc limit 1)
ORDER BY next_date desc limit 2


自助餐的另一种方式是加入餐桌...

有没有一种方法可以优化表格

最佳答案

这是另一种方式:

SELECT next_date, date_diff
 FROM (SELECT *,
               @dateDiff := datediff(next_date, curdate()) AS date_diff,
               @pDateDiff :=
                  IF((@dateDiff < 0 AND @dateDiff > @pDateDiff),
                     @dateDiff,
                     @pDateDiff)
                  AS pDateDiff,
               @nDateDiff :=
                  IF((@dateDiff > 0 AND @dateDiff < @nDateDiff),
                     @dateDiff,
                     @nDateDiff)
                  AS nDateDiff
          FROM activity, (SELECT @pDateDiff := -9999, @nDateDiff := 9999) tmp
          WHERE id = 1) aView
 WHERE date_diff IN (@pDateDiff, 0, @nDateDiff)
ORDER BY next_date;


date_diff值提供上一个日期和下一个日期的角度。


选择所有日期,其中id = 1
查找next_datecurdate()之间的日期差并将其存储在用户定义的变量@dateDiff中。
@pDateDiff是另一个变量,它在负@dateDiff值(我们之前的日期)中跟踪最大值
@nDateDiff是另一个变量,它跟踪@dateDiff正值(我们的下一个日期)中的最小值
最后,仅选择(-ve max, 0, +ve min)中的日期。


PS:如果您重复了日期条目,则查询可能会返回所有这些条目。

关于mysql - 使用UNION优化mysql查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15085851/

10-16 13:22