使用 MySQL 取出當前日期和前一天日期?


使用 CURDATE() 可以取出當前日期,使用 INTERVAL 1 DAY 的 DATE_SUB() 可以取出前一天日期。語法如下

SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY);

語法如下,使用 date_sub() 取出當前日期和前一天日期。

SELECT *FROM yourTableName WHERE yourColumnName = CURDATE() OR yourColumnName = DATE_SUB(CURDATE(),INTERVAL 1 DAY);

為了理解上述語法,我們建立一張表。建立表的查詢如下

mysql> create table ProductDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(20),
   -> ProductOfferDate datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.54 sec)

使用 insert 命令向表中插入一些記錄。此處,我們添加了產品和產品優惠日期。查詢如下

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-11','2017-05-21');
Query OK, 1 row affected (0.25 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-22','2019-01-15');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-21','2019-01-14');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-91','2018-10-23');
Query OK, 1 row affected (0.26 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-133','2019-01-24');
Query OK, 1 row affected (0.13 sec)

使用 select 語句從表中顯示所有記錄。查詢如下

mysql> select *from ProductDemo;

以下是輸出

+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
| 1 | Product-11 | 2017-05-21 00:00:00 |
| 2 | Product-22 | 2019-01-15 00:00:00 |
| 3 | Product-21 | 2019-01-14 00:00:00 |
| 4 | Product-91 | 2018-10-23 00:00:00 |
| 5 | Product-133 | 2019-01-24 00:00:00 |
+----+-------------+---------------------+
5 rows in set (0.00 sec)

以下是取出產品當前日期和前一天日期的查詢

mysql> select *from ProductDemo
   -> where ProductOfferDate = CURDATE() OR ProductOfferDate = date_sub(curdate(),interval 1 day);

以下是輸出

+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
|  2 | Product-22  | 2019-01-15 00:00:00 |
|  3 | Product-21  | 2019-01-14 00:00:00 |
+----+-------------+---------------------+
2 rows in set (0.00 sec)

更新於: 30-Jul-2019

2K+ 瀏覽

開啟你的職業生涯 (Kickstart Your Career)

透過完成課程獲得認證

開始
廣告
© . All rights reserved.