如何在MySQL时间戳字段中搜索日期?
您可以为此使用MySQL的DATE()函数。让我们首先创建一个表-
create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentAdmissionDate timestamp );
使用插入命令在表中插入一些记录-
insert into DemoTable(StudentAdmissionDate) values('2011-01-12 12:34:43'); insert into DemoTable(StudentAdmissionDate) values('2012-10-23 11:32:21'); insert into DemoTable(StudentAdmissionDate) values('2001-02-14 05:12:01'); insert into DemoTable(StudentAdmissionDate) values('2018-12-31 15:10:04'); insert into DemoTable(StudentAdmissionDate) values('2019-04-16 11:04:10');
以下是使用select语句显示表中所有记录的查询-
select *from DemoTable;
这将产生以下输出-
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 1 | 2011-01-12 12:34:43 | | 2 | 2012-10-23 11:32:21 | | 3 | 2001-02-14 05:12:01 | | 4 | 2018-12-31 15:10:04 | | 5 | 2019-04-16 11:04:10 | +-----------+----------------------+ 5 rows in set (0.00 sec)
这是在时间戳字段中搜索日期的查询。
select *from DemoTable where date(StudentAdmissionDate)='2001-02-14';
这将产生以下输出-
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 3 | 2001-02-14 05:12:01 | +-----------+----------------------+ 1 row in set (0.04 sec)
我们还可以搜索给定范围之间的日期:
select *from DemoTable where StudentAdmissionDate >='2012-01-01' and StudentAdmissionDate < '2019-12-01';
这将产生以下输出-
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 2 | 2012-10-23 11:32:21 | | 4 | 2018-12-31 15:10:04 | | 5 | 2019-04-16 11:04:10 | +-----------+----------------------+ 3 rows in set (0.00 sec)