使用 MySQL 獲取不同列中值的時間差


為此,你可以使用 time_format() 和 time_diff()。要查詢時間差,你需要使用 time_diff() 方法。我們首先建立一個表 -

mysql> create table DemoTable624 (PunchIn datetime,PunchOut datetime);
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable624 values('2019-07-14 12:10:00', '2019-07-14 12:50:00');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable624 values('2019-07-14 11:00:00', '2019-07-14 11:30:00');
Query OK, 1 row affected (0.34 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable624;

這將生成以下輸出 -

+---------------------+---------------------+
| PunchIn             | PunchOut            |
+---------------------+---------------------+
| 2019-07-14 12:10:00 | 2019-07-14 12:50:00 |
| 2019-07-14 11:00:00 | 2019-07-14 11:30:00 |
+---------------------+---------------------+
2 rows in set (0.00 sec)

以下是獲取時間差的查詢 -

mysql> select time_format(timediff(PunchIn,PunchOut),'%H hrs, %i min.') from DemoTable624;

這將生成以下輸出 -

+-----------------------------------------------------------+
| time_format(timediff(PunchIn,PunchOut),'%H hrs, %i min.') |
+-----------------------------------------------------------+
| -00 hrs, 40 min.                                          |
| -00 hrs, 30 min.                                          |
+-----------------------------------------------------------+
2 rows in set (0.00 sec)

更新於: 2019 年 8 月 23 日

688 次瀏覽

開啟你的職業生涯之路

完成課程可獲得認證

開始學習
廣告