從當前日期往前的過去 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+ 瀏覽

開啟你的 職業生涯

透過完成課程進行驗證

立即開始
廣告