要从新闻表中选择最近6个月的记录,请使用MySQL中的date_sub()函数,因为新闻记录是根据日期排列的。
语法如下-
select *from yourTableName where yourDateTimeColumnName >= date_sub(now(),interval 6 month);
要了解上述概念,让我们首先创建一个仅包含NEWS ID和发布日期的NEWS表-
mysql> create table Newstable -> ( -> NewsId int, -> NewsDatetime datetime -> );
使用insert命令在表中插入记录。查询如下-
mysql> insert into Newstable values(101,'2018-2-10'); mysql> insert into Newstable values(102,'2018-12-10'); mysql> insert into Newstable values(103,'2018-3-14'); mysql> insert into Newstable values(104,'2018-12-12'); mysql> insert into Newstable values(105,'2018-4-21'); mysql> insert into Newstable values(106,'2018-6-30');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from Newstable;
输出结果
+--------+---------------------+ | NewsId | NewsDatetime | +--------+---------------------+ | 101 | 2018-02-10 00:00:00 | | 102 | 2018-12-10 00:00:00 | | 103 | 2018-03-14 00:00:00 | | 104 | 2018-12-12 00:00:00 | | 105 | 2018-04-21 00:00:00 | | 106 | 2018-06-30 00:00:00 | +--------+---------------------+ 6 rows in set (0.00 sec)
以下是从新表中选择过去6个月的查询。查询如下-
mysql> select *from Newstable where NewsDatetime > date_sub(now(),Interval 6 month);
输出结果
+--------+---------------------+ | NewsId | NewsDatetime | +--------+---------------------+ | 102 | 2018-12-10 00:00:00 | | 104 | 2018-12-12 00:00:00 | | 106 | 2018-06-30 00:00:00 | +--------+---------------------+ 3 rows in set (0.00 sec)