MYSQL 兩個datetime型別相減
阿新 • • 發佈:2019-02-06
原始資料表資料:
select (atime - btime) sec from 資料表;
相減得到的並不是秒,特別需要注意!
結果:
mysql中計算兩個Datetime型別的時間間隔(單位為秒),需要轉換:
1.跨天,月,年都無問題
select (UNIX_TIMESTAMP(atime) - UNIX_TIMESTAMP(btime)) sec
from 資料表;
2.只能用在Time型別,跨天,月,年都有問題
select (TIME_TO_SEC(atime) - TIME_TO_SEC(btime)) sec
from 資料表;
select (TIME_TO_SEC(end_time) -TIME_TO_SEC(start_time)) sec from task_detail where end_time is not null;
結果同上圖所示;
修改資料:
update task_detail set end_time = now() where id = 8;
查詢結果為負值,具體見截圖:
故在做兩個日期相減的時候,採用(TIME_TO_SEC(atime) - TIME_TO_SEC(btime)) sec 方式比較好。