利用 MySQL 找出两个时间戳之间的天数差


使用 MySQL 中的 DATEDIFF() 函数来获取两个时间戳之间的天数差。

语法如下 −

select datediff(yourColumnName1,yourColumnName2) as anyVariableName from yourTableName;

为了理解上述语法,我们先创建一个表。以下是创建表的查询 −

mysql> create table DifferenceTimestamp
   −> (
   −> IssueTime timestamp,
   −> DueTime timestamp
   −> );
Query OK, 0 rows affected (0.66 sec)

在表中插入一些记录以帮助进行插入命令。我们在设置日期。查询如下 −

mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -30 Day));
Query OK, 1 row affected (0.12 sec)

mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -24 Day));
Query OK, 1 row affected (0.16 sec)

mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -5 Day));
Query OK, 1 row affected (0.14 sec)

在表的帮助下,用 select 语句显示来自表的所有记录。查询如下 −

mysql> select *from DifferenceTimestamp;

以下是输出 −

+---------------------+---------------------+
| IssueTime           | DueTime             |
+---------------------+---------------------+
| 2018-12-07 17:48:28 | 2018-11-07 17:48:28 |
| 2018-12-07 17:48:40 | 2018-11-13 17:48:40 |
| 2018-12-07 17:48:46 | 2018-12-02 17:48:46 |
+---------------------+---------------------+
3 rows in set (0.00 sec)

以下是查询两个时间戳之间天数差的示例。查询如下 −

mysql> SELECT DATEDIFF(IssueTime, DueTime) AS DifferenceInTimestampDays from DifferenceTimestamp;

以下是输出 −

+---------------------------+
| DifferenceInTimestampDays |
+---------------------------+
|                        30 |
|                        24 | 
|                         5 |
+---------------------------+
3 rows in set (0.00 sec)

更新于: 2019-07-30

638 浏览量

开启你的职业生涯

完成课程后获得认证

开始学习
广告