0

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

表结构如下

| 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 和 previous_day next_day = 当前日期之后的 next_date previous_day = current_date 之前的 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

其他方式来做它自己加入表......

有没有办法优化表

4

1 回答 1

1

这是另一种方式:

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_diffvalue 给出了上一个和下一个日期的观点。

  • 选择所有日期id = 1
  • next_date查找和&之间的日期差异curdate()存储在用户定义的变量@dateDiff中。
  • @pDateDiff 是另一个变量,它跟踪负值中的最大值@dateDiff(我们之前的日期)
  • @nDateDiff 是另一个变量,它跟踪正值中@dateDiff的最小值(我们的下一个日期)
  • 最后,只选择那些在(-ve max, 0, +ve min).

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

于 2013-02-26T10:50:24.497 回答