MySQL如何减去两个DATETIME和INT值

时间:2014-10-23 04:20:13

标签: mysql

我存储" start_time"," finish_time"和"饭"时间

start_time = DATETIME
finish_time = DATETIME
meal = INT - store minitues

现在我想在start_time,finish_time之间得到尊重,之后我想减去用餐时间如何做到这一点,

eg:
start_time             finish_time           meal
2014-10-24 08:30:00    2014-10-24 18:30:00   45

输出应为: 9:15

如何仅使用MySQL,

我尝试使用TIMESTAMPDIFF,但我不知道如何减去膳食并将其转换为H:m格式:

TIMESTAMPDIFF(MINUTE,start_time, finish_time)

3 个答案:

答案 0 :(得分:1)

做普通的减法:

TIMESTAMPDIFF(MINUTE,start_time, finish_time) - meal

要将其转换为H:m格式,请将其除以60并从60获得模数:

CONCAT(FLOOR((TIMESTAMPDIFF(MINUTE,start_time, finish_time) - meal)/60),
      ':', 
      (TIMESTAMPDIFF(MINUTE,start_time, finish_time) - meal) % 60)

答案 1 :(得分:1)

有一种更好的方法:

SEC_TO_TIME(TIMESTAMPDIFF(MINUTE,start_time, finish_time))

答案 2 :(得分:0)

SELECT 
    SEC_TO_TIME(
        (
            (
                UNIX_TIMESTAMP(`finish_time`) - UNIX_TIMESTAMP(`start_time`) /* difference in seconds */
            ) / 60 - `meal` /* transform in minutes, substract minutes */
        ) * 60 /* seconds again */
    ) AS `timediff` /* to time :) */
FROM `table`