MySQL 选择 30 天范围内的日期?

mysqlmysqli database

要选择 30 天范围内的日期,您可以使用算术运算 - 带间隔。

语法如下 −

select *from yourTableName
where yourDateColumnName > NOW() - INTERVAL 30 DAY
and yourDateColumnName < NOW() + INTERVAL 30 DAY;

为了理解上述语法,让我们创建一个表。创建表的查询如下 −

mysql> create table selectDatesDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ArrivalDate datetime
   -> );
Query OK, 0 rows affected (0.77 sec)

现在,您可以使用 insert 命令在表中插入一些记录。查询如下 −

mysql> insert into selectDatesDemo(ArrivalDate) values('2019-01-10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectDatesDemo(ArrivalDate) values('2019-01-29');
Query OK, 1 row affected (0.21 sec)
mysql> insert into selectDatesDemo(ArrivalDate) values('2019-02-13');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectDatesDemo(ArrivalDate) values('2019-02-19');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectDatesDemo(ArrivalDate) values('2018-02-13');
Query OK, 1 row affected (0.17 sec)
mysql> insert into selectDatesDemo(ArrivalDate) values('2018-03-13');
Query OK, 1 row affected (0.19 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from selectDatesDemo;

这是输出 −

+----+---------------------+
| Id | ArrivalDate         |
+----+---------------------+
| 1  | 2019-01-10 00:00:00 |
| 2  | 2019-01-29 00:00:00 |
| 3  | 2019-02-13 00:00:00 |
| 4  | 2019-02-19 00:00:00 |
| 5  | 2018-02-13 00:00:00 |
| 6  | 2018-03-13 00:00:00 |
+----+---------------------+
6 rows in set (0.00 sec)

以下是选择 30 天范围内日期的查询 −

mysql> select *from selectDatesDemo
   -> where ArrivalDate > NOW() - INTERVAL 30 DAY
   -> and ArrivalDate < NOW() + INTERVAL 30 DAY;

以下是输出 −

+----+---------------------+
| Id | ArrivalDate         |
+----+---------------------+
| 3  | 2019-02-13 00:00:00 |
| 4  | 2019-02-19 00:00:00 |
+----+---------------------+
2 rows in set (0.04 sec)

相关文章