获取指定月份范围内的记录的 MySQL 查询?
让我们先创建一个表 −
mysql> create table DemoTable1795 ( Name varchar(20), DueDate date ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1795 values('John','2018-07-21'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1795 values('Sam','2019-10-21'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1795 values('Sam','2019-01-10'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1795 values('Mike','2018-12-31'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1795;
将产生以下输出 −
+------+------------+ | Name | DueDate | +------+------------+ | John | 2018-07-21 | | Sam | 2019-10-21 | | Sam | 2019-01-10 | | Mike | 2018-12-31 | +------+------------+ 4 rows in set (0.00 sec)
以下是获取指定月份范围内的记录的查询 −
mysql> select * from DemoTable1795 where (YEAR(DueDate) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) AND MONTH(DueDate) BETWEEN 7 AND 12) OR (YEAR(DueDate) = YEAR(CURRENT_DATE()) AND MONTH(DueDate) BETWEEN 1 AND 7);
将产生以下输出 −
+------+------------+ | Name | DueDate | +------+------------+ | John | 2018-07-21 | | Sam | 2019-01-10 | | Mike | 2018-12-31 | +------+------------+ 3 rows in set (0.00 sec)
广告