mysql - 在查询中计算两次之间的差异

时间:2012-04-09 02:16:46

标签: mysql time

我知道我可以使用PHP来执行此操作,但是想知道是否有办法仅使用查询来计算两次之间的差异?我尝试了下面的查询,但它为时差返回NULL。

我表格中的数据存储为:

| created    | changed    |
+------------+------------+
| 1333643004 | 1333643133 |

我想弄清楚回归的方法:

| 2012-04-05 09:23:24 | 2012-04-05 09:25:33 |     00:02:09 |

我试过了:

SELECT 
    FROM_UNIXTIME(created) AS created, 
    FROM_UNIXTIME(changed) AS changed, 
    TIMEDIFF ( changed, created ) / 60 AS timediff 
FROM content
    WHERE id = 45;

产生了:

| 2012-04-05 09:23:24 | 2012-04-05 09:25:33 | NULL |

1 个答案:

答案 0 :(得分:8)

TIMEDIFF()返回的结果仅限于允许的范围 TIME值。或者,您可以使用任一功能 TIMESTAMPDIFF()UNIX_TIMESTAMP(),两者都返回整数。

我会在两列上调用UNIX_TIMESTAMP()(返回整数),然后减去它们。这将为您提供一个整数,您可以在查询或PHP中转换它。

SELECT 
    UNIX_TIMESTAMP(created) AS created, 
    UNIX_TIMESTAMP(changed) AS changed, 
    changed-created AS difference
FROM content
    WHERE id = 45;

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp