如何在mysql中获取最近6个月的详细信息

时间:2013-06-19 09:28:51

标签: mysql date datediff

有人可以帮助我们获取最近6个月的详细信息。尝试使用stackoverflow和mysql站点中已经提到的答案。但没有得到所需的输出。

我尝试了不同的组合。但不可能。

mysql> select date from bo_rr;
+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-09-14 |
| 2013-09-14 |
| 2013-06-19 |
+------------+
6 rows in set (0.00 sec)

mysql> select date from bo_rr where date > date_sub(now(),interval 6 month);
+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-09-14 |
| 2013-09-14 |
| 2013-06-19 |
+------------+
6 rows in set (0.00 sec)

mysql> select date from bo_rr where date >= date_sub(now(),interval 6 month);
+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-09-14 |
| 2013-09-14 |
| 2013-06-19 |
+------------+
6 rows in set (0.00 sec)

mysql> select date from bo_rr where date < date_sub(now(),interval 6 month);
Empty set (0.00 sec)

mysql> select date from bo_rr where date <= date_sub(now(),interval 6 month);
Empty set (0.00 sec)

mysql> select date from bo_rr where date > date_sub(now(),interval -6 month);
Empty set (0.00 sec)

mysql> select date from bo_rr where date >= date_sub(now(),interval -6 month);
Empty set (0.00 sec)

mysql> select date from bo_rr where date < date_sub(now(),interval -6 month);
+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-09-14 |
| 2013-09-14 |
| 2013-06-19 |
+------------+
6 rows in set (0.00 sec)

mysql> select date from bo_rr where date <= date_sub(now(),interval -6 month);
+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-09-14 |
| 2013-09-14 |
| 2013-06-19 |
+------------+
6 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:2)

由于您有将来的记录,您需要设置开始和结束边界条件。您可以使用BETWEEN方便地执行此操作。

尝试

SELECT date 
  FROM bo_rr 
 WHERE date BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE()

SELECT date 
  FROM bo_rr 
 WHERE date <= CURDATE() 
   AND date >= CURDATE() - INTERVAL 6 MONTH

输出:

+------------+
| date       |
+------------+
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-14 |
| 2013-06-19 |
+------------+