选择月度记录表单数据库

时间:2016-02-19 11:57:03

标签: php mysql sql database datetime

mysql> SELECT * FROM con_transactions;
+------+------+---------------------+--------+
| t_id | p_id | date                | amount |
+------+------+---------------------+--------+
|   10 |    1 | 2016-02-17 19:24:05 | 1800   |
|   12 |    2 | 2016-02-18 11:40:13 | 200    |
|   17 |    3 | 2016-02-18 11:42:04 | 100    |
|   19 |    4 | 2016-02-18 11:45:43 | 1      |
|   20 |    5 | 2016-02-18 11:45:54 | 999    |
|   21 |    1 | 2016-02-18 11:46:02 | 1500   |
|   41 |    2 | 2016-02-18 17:23:14 | 500    |
|   42 |    3 | 2016-02-18 17:23:14 | 500    |
|   43 |    4 | 2016-02-18 17:23:15 | 500    |
|   44 |    5 | 2016-02-18 17:23:16 | 500    |
|   45 |    1 | 2016-02-18 17:23:16 | 500    |
|   46 |    2 | 2016-02-18 17:23:16 | 500    |
|   47 |    3 | 2016-02-18 17:23:17 | 500    |
|   48 |    4 | 2016-02-18 17:23:17 | 500    |
|   49 |    5 | 2016-02-18 17:23:18 | 500    |
|   50 |    1 | 2016-02-18 17:25:54 | 1000   |
|   51 |    1 | 2016-02-18 17:26:22 | 3000   |
|   52 |    2 | 2016-02-18 17:48:59 | 10     |
|   53 |    1 | 2016-02-18 17:48:59 | 10     |
|   55 |    1 | 2016-02-19 10:20:12 | 1000   |
+------+------+---------------------+--------+

我如何选择当前月份或上个月所有交易记录。整月都不是30天。那么如何使用SELECT查询选择1月或其他月份记录。我试试这个查询

SELECT * FROM con_transactions WHERE date > '2016-01-01 00:00:00' AND date < '2016-02-01 00:00:00';

这不太聪明。

2 个答案:

答案 0 :(得分:6)

使用month()year()直接查找一年中的任何给定月份。

SELECT * FROM con_transactions WHERE year(date)  = 2016 AND month(date) = 1;

答案 1 :(得分:3)

一种方法是使用YYYYMM等格式进行日期比较:

SELECT *
FROM con_transactions
WHERE YEAR(date) * 100 + MONTH(date) = YEAR(CURDATE())*100 + MONTH(CURDATE());

然而,这有一个缺点,即MySQL不能使用WHERE子句的索引。因此,另一种方法是您的方法的变体,但使用该月的第一天:

WHERE date >= str_to_date(concat_ws('-', year(curdate()), month(curdate()), '01'), '%Y-%m-%d) and
      date < str_to_date(concat_ws('-', year(dateadd(curdate(), interval 1 month)), month(dateadd(curdate(), interval 1 month), '01'), '%Y-%m-%d)