使用UNION优化mysql查询

时间:2013-02-26 09:47:26

标签: mysql

我要求获得下一个日期和上一个日期

表结构如下

| 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

其他方式自己加入表...

有没有办法优化表格

1 个答案:

答案 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_datecurdate()之间的日期差异&amp;存储在用户定义的变量@dateDiff中。
  • @pDateDiff是跟踪负@dateDiff值(我们之前的日期)中的最大值的另一个变量
  • @nDateDiff是另一个跟踪正@dateDiff值的最小值的变量(我们的下一个日期)
  • 最后,只选择(-ve max, 0, +ve min)
  • 中的日期

PS:如果您复制了日期条目,那么查询可能会返回所有日期条目。