MySQL 查询选择一周前的行?

mysqlmysqli database

为此,您可以使用 DATEDIFF() 函数。当前日期时间如下 −

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-06-09 19:15:56 |
+---------------------+
1 row in set (0.00 sec)

首先我们创建一个表 −

mysql> create table DemoTable
   -> (
   -> ShippingDate datetime
   -> );
Query OK, 0 rows affected (0.66 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('2019-06-01');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('2019-06-02');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values('2019-06-14');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('2019-05-21');
Query OK, 1 row affected (0.24 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+---------------------+
| ShippingDate        |
+---------------------+
| 2019-06-01 00:00:00 |
| 2019-06-02 00:00:00 |
| 2019-06-14 00:00:00 |
| 2019-05-21 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)

以下是选择一周前行的查询。假设当前日期是"2019-06-09"。因此,将选择一周前(即"2019-06-02"之前的行)的行 −

mysql> select *from DemoTable where DATEDIFF(now(),ShippingDate) > 7;

输出

+---------------------+
| ShippingDate        |
+---------------------+
| 2019-06-01 00:00:00 |
| 2019-05-21 00:00:00 |
+---------------------+
2 rows in set (0.00 sec)

相关文章