mysql查询在上个月和下个月之间进行选择

时间:2014-06-06 16:48:03

标签: mysql sql datetime

尝试选择从上个月开始到下个月末的所有日期:

USE test;

SELECT *  FROM  MyTable
WHERE col_date BETWEEN DATE_ADD(DATE_ADD(NOW(), INTERVAL -1 MONTH)) 
             AND DATE_ADD(DATE_ADD(NOW(), INTERVAL +1 MONTH))

它说我的语法不正确,但我看到DATE_ADD函数的片段就像​​这样使用。

1 个答案:

答案 0 :(得分:1)

您可以使用date_sub()

date_sub(now(), INTERVAL 1 MONTH)

所以查询应该是

USE test;
SELECT * FROM MyTable
WHERE 
col_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH)  AND DATE_ADD(NOW(), INTERVAL 1 MONTH)

这是mysql中的样子

mysql> select date_sub(now(), INTERVAL 1 MONTH) as previous_month , date_add(now(),INTERVAL 1 MONTH) as next_month;
+---------------------+---------------------+
| previous_month      | next_month          |
+---------------------+---------------------+
| 2014-05-06 22:27:35 | 2014-07-06 22:27:35 |
+---------------------+---------------------+
1 row in set (0.01 sec)

mysql> select NOW() - INTERVAL 1 MONTH as previous_month ,NOW() + INTERVAL 1 MONTH as next_month ;
+---------------------+---------------------+
| previous_month      | next_month          |
+---------------------+---------------------+
| 2014-05-06 22:28:39 | 2014-07-06 22:28:39 |
+---------------------+---------------------+