如何查询 MySQL 时间戳字段中的日期?


你可以为此使用 MySQL 的 DATE() 函数。我们首先创建一个表 -

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentAdmissionDate timestamp
);
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable(StudentAdmissionDate) values('2011-01-12 12:34:43');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentAdmissionDate) values('2012-10-23 11:32:21');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentAdmissionDate) values('2001-02-14 05:12:01');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentAdmissionDate) values('2018-12-31 15:10:04');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(StudentAdmissionDate) values('2019-04-16 11:04:10');
Query OK, 1 row affected (0.81 sec)

以下是对表中的所有数据使用 select 语句进行显示的查询 -

mysql> 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)

这是一个用来查询时间戳字段中日期的查询。

mysql> 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)

我们还可以查询一个范围内的日期

mysql> 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)

更新于:30-Jul-2019

708 浏览量

启动你的职业生涯

通过完成课程获得认证

入门
广告