从当前日期往前的过去 3 天的时间段内获取 MySQL 中的记录,添加对应的记录


我们首先创建一个表 -

mysql> create table DemoTable
(
   ProductAmount int,
   PurchaseDate datetime
);
Query OK, 0 rows affected (0.94 sec)

注意 - 假设当前日期是 2010-09-15。

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

mysql> insert into DemoTable values(567,'2019-09-10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(1347,'2019-09-14');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2033,'2019-09-13');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(1256,'2019-09-11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(1000,'2019-09-16');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

这会生成以下输出 -

+---------------+---------------------+
| ProductAmount | PurchaseDate        |
+---------------+---------------------+
|           567 | 2019-09-10 00 :00 :00 |
|          1347 | 2019-09-14 00:00 :00 |
|          2033 | 2019-09-13 00:00 :00 |
|          1256 | 2019-09-11 00:00 :00 |
|          1000 | 2019-09-16 00:00 :00 |
+---------------+---------------------+
5 rows in set (0.00 sec)

下面是现在在 MySQL 查询中使用 now() 函数的查询 -

mysql> select sum(ProductAmount) from DemoTable
   where PurchaseDate > NOW()- interval 3 day;

这会生成以下输出 -

+--------------------+
| sum(ProductAmount) |
+--------------------+
|             4380   |
+--------------------+
1 row in set (0.00 sec)

更新于: 2019 年 10 月 10 日

1K+ 浏览

开启你的 职业生涯

通过完成课程进行验证

立即开始
广告
© . All rights reserved.