使用 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.