我要求获得下一个日期和上一个日期
表结构如下
| 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在当天之后 current_date之前的previous_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
其他方式自己加入表...
有没有办法优化表格
答案 0 :(得分: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_diff
值给出了上一个和下一个日期的视角。
id = 1
next_date
和curdate()
之间的日期差异&amp;存储在用户定义的变量@dateDiff
中。@dateDiff
值(我们之前的日期)中的最大值的另一个变量@dateDiff
值的最小值的变量(我们的下一个日期)(-ve max, 0, +ve min)
。PS:如果您复制了日期条目,那么查询可能会返回所有日期条目。