使用TIMEDIFF(arg1,arg2)計算TIME或DATETIME之間的差值(arg1-arg2),參數類型必須相同,返回類型為TIME。
TIMEDIFF()返回值范圍在-838:59:59到838:59:59之間
SELECT TIMEDIFF('10:00:00','12:00:00') as diff;
SELECT TIMEDIFF('2019-04-14 02:00:00','2019-04-13 02:00:00') as diff;
如果差值超出范圍(-838:59:59到838:59:59), 需要使用TIMESTAMPDIFF(unit,arg1,arg2),結果為arg2-arg1
unit的值:
- MICROSECOND
- SECOND
- MINUTE
- HOUR
- DAY
- WEEK
- MONTH
- QUARTER
- YEAR
SELECT TIMEDIFF('2015-01-14 02:00:00','2019-04-13 02:00:00') as diff;
SELECT TIMESTAMPDIFF(HOUR,'2015-01-14 02:00:00','2019-04-13 02:00:00') as diff;
使用DATEDIFF(arg1,arg2)計算日期天數差,結果為(arg1-arg2),參數類型為DATE,DATETIME或TIMESTAMP,若傳入DATETIME或TIMESTAMP,時間部分會被忽略
SELECT DATEDIFF('2019-01-14','2019-04-13') as diff;
DATEDIFF()傳入參數類型可以不同,即DATEDIFF(DATE,DATETIME)或DATEDIFF(DATETIME,TIMESTAMP)都可