要获取当前日期以来最后几天的记录,您需要使用DATE_SUB()。我们还将使用NOW()
获取当前日期。语法如下
SELECT *FROM yourTableName WHERE yourDateTimeColumnName BETWEEN DATE_SUB(DATE(NOW()), INTERVAL 2 DAY) AND DATE_SUB(DATE(NOW()), INTERVAL 1 DAY);
让我们看一个例子
mysql> create table get2daysAgoDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(20), - > PostDateTime datetime - > );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('Larry',now()); mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('Mike','2019-02-13'); mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('Sam','2019-01-31'); mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('Bob','2019-02-14'); mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('David','2019-02-12'); mysql> insert into get2daysAgoDemo(Name,PostDateTime) values('Carol','2019-02-11');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from get2daysAgoDemo;
以下是输出
+----+-------+---------------------+ | Id | Name | PostDateTime | +----+-------+---------------------+ | 1 | Larry | 2019-02-15 21:47:10 | | 2 | Mike | 2019-02-13 00:00:00 | | 3 | Sam | 2019-01-31 00:00:00 | | 4 | Bob | 2019-02-14 00:00:00 | | 5 | David | 2019-02-12 00:00:00 | | 6 | Carol | 2019-02-11 00:00:00 | +----+-------+---------------------+ 6 rows in set (0.00 sec)
这是查询以获取最近两天的记录。假设当前日期为2019-02-15
mysql> select *from get2daysAgoDemo - > where PostDateTime between DATE_SUB(DATE(NOW()), INTERVAL 2 DAY) - > AND DATE_SUB(DATE(NOW()), INTERVAL 1 DAY);
以下是显示最近2天(即2月13日和14日)的记录的输出,因为我们当前的日期是2月15日
+----+------+---------------------+ | Id | Name | PostDateTime | +----+------+---------------------+ | 2 | Mike | 2019-02-13 00:00:00 | | 4 | Bob | 2019-02-14 00:00:00 | +----+------+---------------------+ 2 rows in set (0.01 sec)